其他分享
首页 > 其他分享> > RestClient 写法

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;
    }
}

 

标签:RestClient,url,request,param,String,new,写法,restPath
来源: https://www.cnblogs.com/wangquanyi/p/11640879.html