Backend——"Java-RestTemplate as interface docking

Requester------------------------------------------------ -------------------------------------------------- -------------------------------------------------- ------------

 

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.util.*;

/*客户端请求方*/
public class TestClient {
    protected static final Logger log = LoggerFactory.getLogger(TestClient.class);

    /*普通的http接口*/
    protected static RestTemplate restTemplate;

    /*https接口*/
    protected static RestTemplate httpsRestTemplate;

    /*接口地址*/
    private String url = "http://localhost:8088/interface/adduser";

    /*初始化*/
    static {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10000);
        requestFactory.setReadTimeout(10000);
        restTemplate = new RestTemplate(requestFactory);
        log.info("RestTemplate init success");
        try {
            TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
            SSLConnectionSocketFactory connectionSocketFactory =
                    new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
            HttpClientBuilder httpClientBuilder = HttpClients.custom();
            httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
            CloseableHttpClient httpClient = httpClientBuilder.build();
            HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
            factory.setHttpClient(httpClient);
            factory.setConnectTimeout(10 * 1000);
            factory.setReadTimeout(10 * 1000);
            httpsRestTemplate = new RestTemplate(factory);
        } catch (Exception e) {
            log.error("创建HttpsRestTemplate失败", e);
            throw new RuntimeException("创建HttpsRestTemplate失败", e);
        }
    }

    /*post传输,json格式*/
    private String postData(Map<String, String> postParams) throws Exception {
        HttpHeaders headers = new HttpHeaders();
         /*设置请求头*/
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        /*postParams是要传输的参数*/
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(postParams, headers);
        /*post方式传输,如果是http接口就用restTemplate,https接口就用httpsRestTemplate*/
        String result = restTemplate.postForObject(url, httpEntity, String.class);
        return result;
    }

    /*post传输,x-www-form-urlencoded格式,注意此格式需要参数是MultiValueMap类型的,
     MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>()*/
    private String postData(MultiValueMap<String, Object> postParams) throws Exception{
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/x-www-form-urlencoded;charset=UTF-8"));
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(postParams,headers);
        String result =restTemplate.postForObject(url, httpEntity, String.class);
        return result;
    }

    /*get传输,这几种传输方式根据要求选择一种即可*/
    private String getData(Map<String, String> params) throws Exception {
        /*biludParamerUrl(params)方法是把map拼接成key1=value1&key2=value2的参数*/
        String urlWithParam=url+"?"+biludParamerUrl(params);
        String result = restTemplate.getForObject(urlWithParam, String.class);
        return result;
    }

}

 

receiver------------------------------------------------ -------------------------------------------------- -------------------------------------------------- ----------- 

@RestController
@RequestMapping("interface")
public class ServerController {
    private static Logger LOGGER = LoggerFactory.getLogger(ServerController.class);

    @RequestMapping(value = "adduser", method = RequestMethod.POST)
    public UserResponse adduser(@RequestBody User user) {
        LOGGER.info("进入接口进行后续业务操作");
        /*自定义封装的一些返回信息*/
        return userResponse;
    }
}

Guess you like

Origin blog.csdn.net/nienianzhi1744/article/details/99961350