http发送get/post调用,传参为json对象

1.http 请求工具类

 

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * description: http 请求工具类
 */
public class HttpJsonUtil {
    public static final String reqSystemID = "aweb";
    public static final String reqSystemName = "aweb端";

    /**
     * description: 发送http get 请求
     * @param url
     * @param body josn参数
     * @param headerInfo josn参数
     * @return java.lang.String
     */
    public static String doHttpGet(String url, JSONObject body, JSONObject headerInfo) {

        //获取时间、流水
//    String format = headerInfo.containsKey("format") ? headerInfo.getString("format") : "yyyyMMddHHmmssSSS";
        String time = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        int random = (int) (Math.random()*1000);
        String serialNo = time + String.format("%03d",random);
        try {
            //获取当前用户信息
            String operatorID = headerInfo.getString("name");
            String operatorName = headerInfo.getString("nickname");
            //设置http请求头数据
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.set("operatorID", operatorID);
            headers.set("operatorName", URLEncoder.encode(operatorName,"utf-8"));
            headers.set("reqSystemID", reqSystemID);
            headers.set("reqSystemName", URLEncoder.encode(reqSystemName,"utf-8"));
            headers.set("reqSystemDate", time.substring(0,8));
            headers.set("reqSystemTime", time.substring(8,14));
            headers.set("reqSystemSerialNO", serialNo);
            //设置http请求数据
            HttpEntity request = new HttpEntity(body, headers);
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.setRequestFactory(new HttpComponentsClientRestfulHttpRequestFactory());
            restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            System.out.println(restTemplate + "==========zhs=========" + request);
            //发起http的get请求
//            JSONObject resultJson1 = restTemplate.getForObject(url, JSONObject.class, request);
            ResponseEntity<JSONObject> resultJson = restTemplate.exchange(url, HttpMethod.GET, request, JSONObject.class);
            //返回响应报文体
            System.out.println("body=========" + resultJson.getBody());
//            if("200".equals(resultJson.getBody().get("code"))) {
//                return JSONObject.toJSONString(resultJson.getBody());
//            }else{
//                System.out.println("status========" + resultJson.getBody().get("msg"));
//                return resultJson.getBody().toJSONString();
//            }
            return JSONObject.toJSONString(resultJson.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * description: 发送http post 请求
     * @param url
     * @param body josn参数
     * @param headerInfo josn参数
     * @return java.lang.String
     */
    public static String doHttpPost(String url, JSONObject body, JSONObject headerInfo) {
        //获取时间、流水
//    String format = headerInfo.containsKey("format") ? headerInfo.getString("format") : "yyyyMMddHHmmssSSS";
        String time = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        int random = (int) (Math.random()*1000);
        String serialNo = time + String.format("%03d",random);
        try {
            //获取当前用户信息
            String operatorID = headerInfo.getString("name");
            String operatorName = headerInfo.getString("nickname");
            //设置http请求头数据
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.set("operatorID", operatorID);
            headers.set("operatorName", URLEncoder.encode(operatorName,"utf-8"));
            headers.set("reqSystemID", reqSystemID);
            headers.set("reqSystemName", URLEncoder.encode(reqSystemName,"utf-8"));
            headers.set("reqSystemDate", time.substring(0,8));
            headers.set("reqSystemTime", time.substring(8,14));
            headers.set("reqSystemSerialNO", serialNo);
            //设置http请求数据
            HttpEntity request = new HttpEntity(body, headers);
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.setRequestFactory(new HttpComponentsClientRestfulHttpRequestFactory());
            restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            System.out.println(restTemplate + "==========zhs=========" + request);
            //发起http的post请求
            JSONObject resultJson1 = restTemplate.postForObject(url, request, JSONObject.class);
            ResponseEntity<JSONObject> resultJson = restTemplate.exchange(url, HttpMethod.POST, request, JSONObject.class);
            //返回响应报文体
            System.out.println("body=========" + resultJson.getBody());
//            if("200".equals(resultJson1.getJSONObject("data").getJSONObject("appHead").get("status"))){
//                return JSONObject.toJSONString(resultJson1.getJSONObject("data"));
//            }
            return JSONObject.toJSONString(resultJson.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

 

 

 

2.Http组件客户端Restful Http请求工厂

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

import java.net.URI;

public class HttpComponentsClientRestfulHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {

    @Override
    protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
        if (httpMethod == HttpMethod.GET) {
            return new HttpGetRequestWithEntity(uri);
        }
        return super.createHttpUriRequest(httpMethod, uri);
    }
    private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
        public HttpGetRequestWithEntity(final URI uri) {
            super.setURI(uri);
        }

        @Override
        public String getMethod() {
            return HttpMethod.GET.name();
        }
    }

}

注意:1.用合适的jar,否则代码会报错

   2.用下面代码发post会请求两次,

//第一种
ResponseEntity<JSONObject> resultJson = restTemplate.exchange(url, HttpMethod.POST, request, JSONObject.class);
//第二种
JSONObject resultJson1 = restTemplate.postForObject(url, request, JSONObject.class);

 

posted @ 2022-08-21 21:07  借你耳朵说爱你  阅读(1515)  评论(0编辑  收藏  举报