java springboot 初体验 (九)对接http请求

  1. 上一篇
    1.   java springboot 初体验 (八)对接swagger2
    2. https://www.cnblogs.com/zwjvzwj/p/16614128.html
  2. 使用Java调用http请求的6种方式

    1. 使用HttpURLConnection调用http请求
    2. 使用commons-httpclient调用http请求
    3. 使用org.apache.httpcomponents调用http请求
    4. 使用OkHttp调用http请求
    5. 使用RestTemplate调用http请求
    6. 使用OpenFeign调用http请求
  3. package com.zwj.zwjproject.utils;
    
    import com.google.gson.Gson;
    import com.zwj.zwjproject.interceptor.TraceInterceptor;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.httpclient.Header;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.methods.RequestEntity;
    import org.apache.commons.httpclient.methods.StringRequestEntity;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    import org.slf4j.MDC;
    import org.springframework.stereotype.Component;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Map;
    
    /**
     * @ClassName: HttpCommonsHttpClientUtil
     * @Author zhangwujie
     * @Date 2022/8/22 8:53 下午
     * @Description:
     */
    @Slf4j
    @Component
    public class HttpCommonsHttpClientUtil {
    
        private static final Gson gson = new Gson();
    
        public String doJsonPostFromMap(String url,Map<String, Object> bodyMap) throws Exception {
            // 2.请求参数
            String bodyString = gson.toJson(bodyMap);
            // 3.创建连接
            HttpClient httpClient = new HttpClient();
            // 设置连接参数url
            PostMethod postMethod = new PostMethod(url);
            // 设置连接参数请求类型
            postMethod.addRequestHeader("Content-Type", "application/json");
            // 设置连接参数链路追踪traceId
            postMethod.addRequestHeader(TraceInterceptor.TRACE_ID, MDC.get(TraceInterceptor.TRACE_ID));
            // 设置连接参数请求参数
            RequestEntity entity = new StringRequestEntity(bodyString, "application/json", "UTF-8");
            postMethod.setRequestEntity(entity);
            // 解决返回值中文乱码
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            // 4.发起请求
            log.info("HttpCommonsHttpClientUtil doJsonPostFromMap url={} reqBody={}", url, bodyString);
            int code = httpClient.executeMethod(postMethod);
            // 5.接收返回值
            String respBody = postMethod.getResponseBodyAsString();
            log.info("HttpCommonsHttpClientUtil doJsonPostFromMap httpStatus={} respBody={}", code, respBody);
            if (code != 200) {
                throw new Exception("调用服务端异常");
            }
            // 6.关闭连接
            postMethod.releaseConnection();
            return respBody;
        }
    }

     

  4. package com.zwj.zwjproject.utils;
    
    import com.google.gson.Gson;
    import com.zwj.zwjproject.interceptor.TraceInterceptor;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.util.EntityUtils;
    import org.slf4j.MDC;
    import org.springframework.stereotype.Component;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Map;
    
    /**
     * @ClassName: HttpComponentsUtil
     * @Author zhangwujie
     * @Date 2022/8/22 8:53 下午
     * @Description:
     */
    @Slf4j
    @Component
    public class HttpComponentsUtil {
    
        private static final Gson gson = new Gson();
    
        public String doJsonPostFromMap(String url,Map<String, Object> bodyMap) throws Exception {
            // 2.请求参数JSON格式
            String bodyString = gson.toJson(bodyMap);
            // 3.创建连接与设置连接参数
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(bodyString);
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            // 设置header链路追踪
            httpPost.addHeader(TraceInterceptor.TRACE_ID, MDC.get(TraceInterceptor.TRACE_ID));
            // 4.发起请求与接收返回值
            log.info("HttpComponentsUtil doJsonPostFromMap url={} reqBody={}", url, httpPost);
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity res = response.getEntity();
            String respBody = EntityUtils.toString(res);
            log.info("HttpComponentsUtil doJsonPostFromMap httpStatus={} respBody={}", statusCode, respBody);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Exception("调用服务端异常.");
            }
            // 5.关闭连接
            httpClient.close();
            return respBody;
        }
    }

     

  5. package com.zwj.zwjproject.utils;
    
    import com.google.gson.Gson;
    import com.zwj.zwjproject.interceptor.TraceInterceptor;
    import lombok.extern.slf4j.Slf4j;
    import org.slf4j.MDC;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.MediaType;
    import org.springframework.stereotype.Component;
    import org.springframework.web.client.RestTemplate;
    
    import java.util.Map;
    
    /**
     * @ClassName: HttpRestTemplateUtil
     * @Author zhangwujie
     * @Date 2022/8/22 8:53 下午
     * @Description:
     */
    @Slf4j
    @Component
    public class HttpRestTemplateUtil {
    
        private static final Gson gson = new Gson();
    
        public String doJsonPostFromMap(String url,Map<String, Object> bodyMap) throws Exception {
            // 2.请求参数JSON格式
            String bodyString = gson.toJson(bodyMap);
            // 3.创建RestTemplate
            RestTemplate restTemplate = new RestTemplate();
            // 4.设置RestTemplate参数(请求头和body)
            HttpHeaders headers = new HttpHeaders();
            MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(mediaType);
            headers.add("Accept", "application/json");
            // 设置header链路追踪
            headers.add(TraceInterceptor.TRACE_ID, MDC.get(TraceInterceptor.TRACE_ID));
            log.info("HttpRestTemplateUtil doJsonPostFromMap url={} reqBody={}", url, bodyString);
            HttpEntity<String> entity = new HttpEntity<>(bodyString, headers);
            // 5.使用RestTemplate发起请求与接收返回值
            String respBody = restTemplate.postForObject(url, entity, String.class);
            log.info("HttpRestTemplateUtil doJsonPostFromMap respBody={}", respBody);
            return respBody;
        }
    }

     

  6. package com.zwj.zwjproject.utils;
    
    import com.google.gson.Gson;
    import com.zwj.zwjproject.interceptor.TraceInterceptor;
    import kong.unirest.HttpRequestWithBody;
    import kong.unirest.HttpResponse;
    import kong.unirest.JsonNode;
    import kong.unirest.Unirest;
    import lombok.extern.slf4j.Slf4j;
    import org.slf4j.MDC;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.MediaType;
    import org.springframework.stereotype.Component;
    import org.springframework.web.client.RestTemplate;
    
    import java.util.Map;
    
    /**
     * @ClassName: HttpUnirestUtil
     * @Author zhangwujie
     * @Date 2022/8/22 8:53 下午
     * @Description:
     */
    @Slf4j
    @Component
    public class HttpUnirestUtil {
    
        private static final Gson gson = new Gson();
    
        public String doJsonPostFromMap(String url, Map<String, Object> bodyMap) throws Exception {
            // 2.请求参数JSON格式
            String bodyString = gson.toJson(bodyMap);
            log.info("HttpUnirestUtil doJsonPostFromMap url={} reqBody={}", url, bodyString);
            HttpResponse<JsonNode> response = Unirest.post(url)
                    .header("Content-Type", "application/json")
                    .header(TraceInterceptor.TRACE_ID, MDC.get(TraceInterceptor.TRACE_ID))
                    .body(bodyString)
                    .asJson();
            String respBody = response.getBody().toString();
            int httpStatus = response.getStatus();
            log.info("HttpUnirestUtil doJsonPostFromMap httpStatus={} respBody={}", httpStatus, respBody);
            return respBody;
        }
    }

     

  7. 下一篇
    1.   java springboot 初体验 (十)对接ut
    2. https://www.cnblogs.com/zwjvzwj/p/16616151.html
posted @ 2022-08-23 14:46  zwjvzwj  阅读(164)  评论(0编辑  收藏  举报