zoukankan      html  css  js  c++  java
  • RestClient 写法

    代码:

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.http.*;
    import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
    import org.springframework.http.converter.*;
    import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
    import org.springframework.stereotype.Component;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.util.MimeType;
    import org.springframework.util.MimeTypeUtils;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.client.RestTemplate;
    
    import java.io.File;
    import java.nio.charset.Charset;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    
    @Component
    @Slf4j
    public class RestClient {
    
        @Value("${rest.url}")
        private String url_1;
    
        @Value(("${rest.username}"))
        private String username;
    
        @Value(("${rest.password}"))
        private String password;
    
        private  RestTemplate rest = null;
        
        public  String getByRest(String restPath, String param) throws Exception {
            ResponseEntity<String> request = request(restPath, HttpMethod.GET, param);
            return request.getBody();
        }
        
        public  byte[] getByImage(String restPath, String param) throws Exception {
            ResponseEntity<byte[]> request = request_image(restPath, HttpMethod.GET, param);
            return request.getBody();
        }
        
        public  String postByRest(String restPath, Map map) throws Exception {
            ResponseEntity<String> request = request_json(restPath, HttpMethod.POST, map);
            return request.getBody();
        }
        public  String postByUpload(String restPath, Map map) throws Exception {
            ResponseEntity<String> request = request_file(restPath, HttpMethod.POST, map);
            return request.getBody();
        }
        
        public  String postByRest(String restPath, String param) throws Exception {
            ResponseEntity<String> request = request_json(restPath, HttpMethod.POST, param);
            return request.getBody();
        }
        
        public  String putByRest(String restPath, Map map) throws Exception {
            ResponseEntity<String> request = request_json(restPath, HttpMethod.PUT, map);
            return request.getBody();
        }
        public  String putByUpload(String restPath, Map map) throws Exception {
            ResponseEntity<String> request = request_file(restPath, HttpMethod.PUT, map);
            return request.getBody();
        }
        
        public  String putByRest(String restPath, String param) throws Exception {
            ResponseEntity<String> request = request_json(restPath, HttpMethod.PUT, param);
            return request.getBody();
        }
        
        
        public  String deleteByRest(String restPath, Map map) throws Exception {
            ResponseEntity<String> request = request_json(restPath, HttpMethod.DELETE, map);
            return request.getBody();
        }
        
        public  String deleteByRest(String restPath, String param) throws Exception {
            ResponseEntity<String> request = request_json(restPath, HttpMethod.DELETE, param);
            return request.getBody();
        }
        public  String deleteByRestFormQuery(String restPath, String param) throws Exception {
            ResponseEntity<String> request = request(restPath, HttpMethod.DELETE, param);
            return request.getBody();
        }
    
        private  ResponseEntity<String> request(String restPath, HttpMethod method, String param) {
           String  url =  url_1+ restPath + "?" + param;
    //        String url = "http://192.168.2.131:8080/api" + restPath + "?" + param;
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<Map<String, Object>> entity = new HttpEntity<Map<String, Object>>(null, headers);
            ResponseEntity<String> exchange = getRest().exchange(url, method, entity, String.class);
            String body = exchange.getBody();
            JSONObject parseObject = JSON.parseObject(body);
            if("-2000".equals(parseObject.getString("code")) || "-10101".equals(parseObject.getString("code"))) {
                String loginUrl = url_1+"/v1/user/login";
                MultiValueMap<String, Object> paramName = new LinkedMultiValueMap<String, Object>();
                paramName.add("username", username);
                paramName.add("password", password);
                String string = rest.postForObject(loginUrl, paramName, String.class);  
                log.info(string);
                if(string.indexOf(""code": 0")!=-1){
                   
                }
                exchange = rest.exchange(url, method, entity, String.class);
            }
            return exchange;
        }
        
        
        private  ResponseEntity<byte[]> request_image(String restPath, HttpMethod method, String param) {
            String url =  url_1+ restPath + "?" + param;
    //       String url = "http://192.168.2.131:8080/api" + restPath + "?" + param;
           HttpHeaders headers = new HttpHeaders();
           MimeType mimeType = MimeTypeUtils.parseMimeType("application/octet_stream");
           MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
           // 请求体
    //       headers.setContentType(mediaType);
           headers.setAccept(Arrays.asList(MediaType.IMAGE_JPEG));
           HttpEntity<byte[]> entity = new HttpEntity<byte[]>(headers);
           ResponseEntity<byte[]> exchange = getRest().exchange(url, method, entity, byte[].class);
           return exchange;
       }
        
        public  String getStructByImage(String type,String imgPath){
            String url = url_1;
            FileSystemResource resource = new FileSystemResource(new File(imgPath));
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
            param.add("type", type);  
            param.add("stream", resource); 
         //   param.add("fileName", "test.txt");     
            String jsonStr = getRest().postForObject(url, param, String.class);
            return jsonStr;
        }
        
        @SuppressWarnings("unchecked")
        private  ResponseEntity<String> request_file(String restPath, HttpMethod method, Map map) {
            String url =  url_1+ restPath;
    //       String url = "http://192.168.2.199:8088/api" + restPath;
            HttpHeaders headers = new HttpHeaders();
            MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
            MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
            // 请求体
    //        headers.setContentType(mediaType);
            // 发送请求
            HttpEntity<Map<String, Object>> entity = new HttpEntity<Map<String, Object>>(map, headers);
            ResponseEntity<String> exchange = getRest().exchange(url, method, entity, String.class);
            String body = exchange.getBody();
            JSONObject parseObject = JSON.parseObject(body);
    
            if("-2000".equals(parseObject.getString("code")) || "-10101".equals(parseObject.getString("code"))) {
                String loginUrl = url_1+"/v1/user/login";
                MultiValueMap<String, Object> paramName = new LinkedMultiValueMap<String, Object>();
                paramName.add("username", username);
                paramName.add("password", password);
                String string = rest.postForObject(loginUrl, paramName, String.class);
                log.info(string);
                if(string.indexOf(""code": 0")!=-1){
    
                }
                exchange = rest.exchange(url, method, entity, String.class);
            }
    
            return exchange;
        }
        
        @SuppressWarnings("unchecked")
        private  ResponseEntity<String> request_json(String restPath, HttpMethod method, Map map) {
             String  url =  url_1 + restPath;
    //        String url = "http://192.168.2.199:8088/api" + restPath;
            HttpHeaders headers = new HttpHeaders();
            MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
            MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
            // 请求体
            headers.setContentType(mediaType);
            HttpEntity<Map<String, Object>> entity = new HttpEntity<Map<String, Object>>(map, headers);
    
            ResponseEntity<String> exchange = getRest().exchange(url, method, entity, String.class);
            String body = exchange.getBody();
            JSONObject parseObject = JSON.parseObject(body);
            if("-2000".equals(parseObject.getString("code")) || "-10101".equals(parseObject.getString("code"))) {
                String loginUrl = url_1+"/api/user/login";
                MultiValueMap<String, Object> paramName = new LinkedMultiValueMap<String, Object>();
                paramName.add("username", username);
                paramName.add("password", password);
                String string = rest.postForObject(loginUrl, paramName, String.class);
                log.info(string);
                if(string.indexOf(""code": 0")!=-1){
    
                }
                exchange = rest.exchange(url, method, entity, String.class);
            }
            return exchange;
        }
        
        private  ResponseEntity<String> request_json(String restPath, HttpMethod method, String param) {
            String url = url_1+ restPath;
    //        String url = "http://localhost:8088" + restPath;
            HttpHeaders headers = new HttpHeaders();
            MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
            MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
            // 请求体
            headers.setContentType(mediaType);
            HttpEntity<String> entity = new HttpEntity<String>(param, headers);
            ResponseEntity<String> exchange = getRest().exchange(url, method, entity, String.class);
            String body = exchange.getBody();
            JSONObject parseObject = JSON.parseObject(body);
            if("-2000".equals(parseObject.getString("code")) || "-10101".equals(parseObject.getString("code"))) {
                String loginUrl = url_1+"/v1/user/login";
                MultiValueMap<String, Object> paramName = new LinkedMultiValueMap<String, Object>();
                paramName.add("username", username);
                paramName.add("password", password);
                String string = rest.postForObject(loginUrl, paramName, String.class);
                log.info(string);
                if(string.indexOf(""code": 0")!=-1){
    
                }
                exchange = rest.exchange(url, method, entity, String.class);
            }
            return exchange;
        }
        
        public  RestTemplate restTemplate() throws Exception { // 这个方法可以让RestTemplate保存session
            HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = null;
            // if(PropertiesUtil.getString("rest.url").startsWith("https")){
            // clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(new SSLClient(PropertiesUtil.getString("rest.jks_path"),
            // PropertiesUtil.getInt("rest.port")));
            // }else{
            clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
    //        clientHttpRequestFactory.setConnectTimeout(PropertiesUtil.getInt("rest.connectTimeout"));
    //        clientHttpRequestFactory.setReadTimeout(PropertiesUtil.getInt("rest.readTimeout"));
    //        clientHttpRequestFactory.setConnectionRequestTimeout(PropertiesUtil.getInt("rest.connectionRequestTimeout"));
            // }
            return new RestTemplate(clientHttpRequestFactory);
        }
        
        public  RestTemplate getRest() {
            try {
                if (rest == null) {
                    rest = restTemplate();
    //              String url = "http://192.168.2.131:8080/bigdata_restful_server/v1/user/login";
    //                MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
    //                param.add("username", "admin");
    //                param.add("password", "123456"); 
    //                String string = rest.postForObject(url, param, String.class);  
    //                log.info(string);
    //                if(string.indexOf(""code": 0")!=-1){
    //                  
    //                }
                    // 添加数据库乱码转换
                    List<HttpMessageConverter<?>> cos = new ArrayList<HttpMessageConverter<?>>();
                    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
                    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
                    
                    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
                    List<HttpMessageConverter<?>> cos2 = new ArrayList<HttpMessageConverter<?>>();
                    cos2.add(stringHttpMessageConverter);
                    cos2.add(new ByteArrayHttpMessageConverter());
                    cos2.add(new ResourceHttpMessageConverter());
                    formHttpMessageConverter.setPartConverters(cos2);
                    cos.add(formHttpMessageConverter);
                    cos.add(stringHttpMessageConverter);
                    cos.add(mappingJackson2HttpMessageConverter);
                    rest.setMessageConverters(cos);
                }
            } catch (Exception e) {
                // TODO: handle exception
                log.error("获取rest对象失败", e);
            }
            return rest;
        }
    }
  • 相关阅读:
    layui flow loading占位图实现方法
    layui弹出层layer的area过大被遮挡
    layui 复选框checkbox 实现全选全选
    axios 设置headers token
    elementUI vue this.$confirm 和el-dialog 弹出框 移动
    vue + axios + formdata 上传文件带参数的爬坑之路
    Java四舍五入时保留指定小数位数
    List containsKey 和Map contains 判断集合中是否包含某个值
    BigDecimal 基本使用 比较大小和加减乘除
    springMVC返回json数据乱码问
  • 原文地址:https://www.cnblogs.com/wangquanyi/p/11640879.html
Copyright © 2011-2022 走看看