我是靠谱客的博主 矮小画板,最近开发中收集的这篇文章主要介绍resttemplate get请求_RestTemplate使用RestTemplate,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

点击  程序员IT课堂 关注我们 42ec8059b109def24ae4aa1de27badf2.png

RestTemplate


Rest发送请求时携带Cookie

List cookieList = new ArrayList<>(4);HttpHeaders requestHeaders = new HttpHeaders();String token = "aaaaa";String cookieUrl = "https://mydomain.com/cookie";cookieList.add("token=" + token);requestHeaders.put("Cookie", cookieList);HttpEntity> requestEntity = new HttpEntity<>(null, requestHeaders);ResponseEntity responseEntity = restTemplate.exchange(        cookieUrl,        HttpMethod.GET,        requestEntity, MyResponse.class);if (responseEntity.getStatusCode() == HttpStatus.OK) {    if (responseEntity.getBody().getCode().equals("1")) {        System.out.println(responseEntity.getBody().getData().toString());    } else {        System.out.println("error" + responseEntity.getBody().getCode());    }}

RestTemplate添加自定义拦截器

/** 自定义restTemplate拦截器* 打印日志*/@Componentclass ActionTrackInterceptor implements ClientHttpRequestInterceptor {@Overridepublic ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {    HttpHeaders headers = httpRequest.getHeaders();    // 加入自定义字段    headers.add("aa", "aa");    traceRequest(httpRequest, bytes);    // 保证请求继续被执行    ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);    traceResponse(response);    return response;}private void traceRequest(HttpRequest request, byte[] body) throws IOException {    log.debug("===========================request begin================================================");    log.debug("URI         : {}", request.getURI());    log.debug("Method      : {}", request.getMethod());    log.debug("Headers     : {}", request.getHeaders());    log.debug("Request body: {}", new String(body, StandardCharsets.UTF_8));    log.debug("==========================request end================================================");}private void traceResponse(ClientHttpResponse response) throws IOException {    StringBuilder inputStringBuilder = new StringBuilder();    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"))) {        String line = bufferedReader.readLine();        while (line != null) {            inputStringBuilder.append(line);            inputStringBuilder.append('n');            line = bufferedReader.readLine();        }    }    log.debug("============================response begin==========================================");    log.debug("Status code  : {}", response.getStatusCode());    log.debug("Status text  : {}", response.getStatusText());    log.debug("Headers      : {}", response.getHeaders());    log.debug("Response body: {}", inputStringBuilder.toString());    log.debug("=======================response end=================================================");}}

在RestTemplate对象创建的地方加入自定义拦截器

 /* * 添加自定义的拦截器 * */restTemplate.getInterceptors().add(new ActionTrackInterceptor());

注意

如果没有配置日志依赖及配置文件,请首先配置依赖及配置文件,否则可能无法使用log在控制台打印日志。

RestTemplate使用httpClient及跳过主机名校验

添加httpClient依赖

    org.apache.httpcomponents    httpclient    4.5.9

使用HttpClient构造RestTemplate对象并配置忽略主机名校验

@Beanpublic RestTemplate skipVerifyRestTemplate() {    SSLConnectionSocketFactory buildSSLSocketFactory = null;    try {        buildSSLSocketFactory = this.buildSSLSocketFactory();    } catch (Exception e) {        e.printStackTrace();    }    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(            HttpClients.custom().setSSLSocketFactory(buildSSLSocketFactory).build());    factory.setConnectionRequestTimeout(5000);    factory.setConnectTimeout(5000);    RestTemplate restTemplate = new RestTemplate();    /*        * 使用BufferingClientHttpRequestFactory包装,否则可能因为拦截器等导致读取到的responseBody为空        * */    restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory));    /*        * 添加自定义的拦截器        * */    restTemplate.getInterceptors().add(new ActionTrackInterceptor());    return restTemplate;}private SSLConnectionSocketFactory buildSSLSocketFactory() throws Exception {    SSLContext sslContext = SSLContext.getInstance("SSL");    // 设置信任证书(绕过TrustStore验证)    sslContext.init(null, new TrustManager[]{new AuthX509TrustManager()}, null);    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());    /*        * hostname,默认返回true,不验证hostname        * 这里使用了lambda表达式,主机名校验接口是HostnameVerifier,可以选择自己的实现类或apache的默认实现        * */    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,            new String[]{"TLSv1"}, null, (urlHostName, session) -> true);    return sslConnectionSocketFactory;}private class AuthX509TrustManager implements TrustManager, X509TrustManager {    @Override    public X509Certificate[] getAcceptedIssuers() {        return null;    }    @Override    public void checkServerTrusted(X509Certificate[] certs, String authType) {        return;    }    @Override    public void checkClientTrusted(X509Certificate[] certs, String authType) {        return;    }}   

日志打印结果

[2020-07-15 16:10:46.279] [main] DEBUG = > ===========================request begin================================================[2020-07-15 16:10:46.280] [main] DEBUG = > URI         : https://mydomain.com[2020-07-15 16:10:46.281] [main] DEBUG = > Method      : GET[2020-07-15 16:10:46.282] [main] DEBUG = > Headers     : [Accept:"application/json, application/*+json", Cookie:"token=12344......", Content-Length:"0", aa:"aa"][2020-07-15 16:10:46.284] [main] DEBUG = > Request body: [2020-07-15 16:10:46.284] [main] DEBUG = > ==========================request end================================================[2020-07-15 16:10:46.621] [main] DEBUG = > ============================response begin==========================================[2020-07-15 16:10:46.622] [main] DEBUG = > Status code  : 200 OK[2020-07-15 16:10:46.623] [main] DEBUG = > Status text  : OK[2020-07-15 16:10:46.623] [main] DEBUG = > Headers      : [Date:"Wed, 15 Jul 2020 08:10:46 GMT", Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Connection:"keep-alive", x-content-type-options:"nosniff", x-xss-protection:"1; mode=block", cache-control:"no-cache, no-store, max-age=0, must-revalidate", "max-age=0", pragma:"no-cache", expires:"0", x-frame-options:"DENY", x-envoy-upstream-service-time:"2", Server:"Guess"][2020-07-15 16:10:46.624] [main] DEBUG = > Response body: {"code":"1","message":"成功","data":{"userID":"111","username":"aaa","email":"aaa@mail.com"}}[2020-07-15 16:10:46.624] [main] DEBUG = > =======================response end=================================================

从restTemplate中读取Cookie信息

HttpHeaders httpHeaders = responseEntity.getHeaders();可以获取到所有的响应header,其中包含了Set-cookie,其value值是一个链表,每个记录包含了cookie的有效期、path、域及HttpReadOnly等

bee243ef9d38a62fa277e1d3b0a5e87c.png

当我们在cookie中设置多个cookie时,获取到的Set-Cookie的值是一个链表

677c8e661d8f35af541a5eb043241a42.png

HttpHeaders requestHeaders = new HttpHeaders();String url = "https://a.com/test";HttpEntity> requestEntity = new HttpEntity<>(null, requestHeaders);ResponseEntity responseEntity = restTemplate.exchange(        url,        HttpMethod.GET,        requestEntity, TreeMap.class);HttpHeaders httpHeaders = responseEntity.getHeaders();String[] cookies = new String[4];httpHeaders.get("Set-Cookie").toArray(cookies);if (cookies != null) {    for (String cookie : cookies) {        log.info(cookie);    }}

异常处理可以在自定义拦截器中统一处理

我们可以在自定义拦截器中统一处理异常信息,比如返回结果与我们传入的结果不是统一类型映射异常,找不到主机等。

traceRequest(httpRequest, bytes);    ClientHttpResponse response;    // 保证请求继续被执行    try {        response = clientHttpRequestExecution.execute(httpRequest, bytes);    } catch (Exception e) {        log.error(e.getMessage(), e);        throw new RuntimeException(String.format("请求接口时发生异常:%s", e.getMessage()));    }traceResponse(response);

如果我们的项目响应状态码为200时才是正常状态,可以在traceResponse方法中判断,如果不是200可以抛出异常等。

084b0a03b1393a2b8d335a5c0b86ce3b.png

服务端收到多个同名cookie

服务端可能接收到多个同名cookie,此时,接收到的cookie是数组,存在同名cookie,如果项目依赖cookie中的值鉴定用户身份,需要考虑多个同名cookie的影响。

客户端

String token = "aaaa";cookieList.add("token=" + token);cookieList.add("token=" + "bbbb");requestHeaders.put("Cookie", cookieList);

服务端

Cookie[] cookies = request.getCookies();            

ca86b0b21111dc18eb94e7f5d11e9198.png

RestTemplate的负载均衡等在之后的SpringCloud中说明。

往期推荐

  • Docker安装

  • Docker运行程序

  • 使用minikube安装kubernetes

950e957c9e87616110c089763e742f54.png

最后

以上就是矮小画板为你收集整理的resttemplate get请求_RestTemplate使用RestTemplate的全部内容,希望文章能够帮你解决resttemplate get请求_RestTemplate使用RestTemplate所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部