首页 > 其他分享 >http发送get/post调用,传参为json对象

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

时间:2022-08-21 21:23:21浏览次数:82  
标签:set http String get JSONObject headers json new

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.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * description: http 请求工具类
 */
public class HttpJsonUtil {

    //获取时间、流水
//    String format = headerInfo.containsKey("format") ? headerInfo.getString("format") : "yyyyMMddHHmmssSSS";
    public static String time = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    public static int random = (int) (Math.random()*1000);
    public static String serialNo = time + String.format("%03d",random);
    public static final String reqSystemID = "web";
    public static final String reqSystemName = "web端";

    /**
     * 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) {
        try {
            //获取当前用户信息
            String operatorID = headerInfo.getString("ID");
            String operatorName = headerInfo.getString("name");
            //设置http请求头数据
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("operatorID", operatorID);
            headers.set("operatorName", operatorName);
            headers.set("reqSystemID", reqSystemID);
            headers.set("reqSystemName", reqSystemName);
            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) {
        try {
            //获取当前用户信息
            String operatorID = headerInfo.getString("ID");
            String operatorName = headerInfo.getString("name");
            //设置http请求头数据
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("operatorID", operatorID);
            headers.set("operatorName", operatorName);
            headers.set("reqSystemID", reqSystemID);
            headers.set("reqSystemName", reqSystemName);
            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();
        }
    }

}

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

标签:set,http,String,get,JSONObject,headers,json,new
From: https://www.cnblogs.com/ZhaoHS/p/16594933.html

相关文章

  • Json用法
    1.什么是jsonJSON(JavaScriptObjectNotation,JS对象简谱)是一种轻量级的数据交换格式。它基于ECMAScript(EuropeanComputerManufacturersAssociation,欧洲计算机协......
  • Live2d Widget
    写在最前最早的时候看别人的博客很多都有一个可爱的看板娘,然后就找了教程给自己也整了一个。因为找到的教程都是稂莠不齐的,原作者自己说的也略显含糊(其实是我自己看不懂)。......
  • Flask 学习-3.设置 HTTP 请求 方法(get/post)
    前言使用route装饰器设置url访问地址,默认是get请求方式,通过methods参数可以设置不同的http请求方法methods参数没有声明请求方式,默认是get请求fromflaskimport......
  • nginx ngx_http_degradation_module 模块
    ngx_http_degradation_module是一个不错的nginx模块,但是官方文档没有写,主要的场景是在低内存的情形下允许Nginx服务器返回444错误或204错误参考使用 http......
  • http缓存学习
    今天项目上线后,上级看了项目来找到我,发现前端页面没有更新,但我访问没问题,于是排除了上线的问题。看了上级未更新页面的控制台,发现页面html文件竟然是从缓存中取得,为啥不同......
  • 向QtableWidget中添加自定义widget崩溃异常: 0xC0000005
    1.问题描述想给QTableWidget添加QCheckBox,代码如下,tableWidget->setCellWidget老是崩溃(0x0F954E63(qwindows.dll)处(位于QStockView.exe中)引发的异常:0xC0000005: ),......
  • Maven中xml配置文件导出到target失败问题解决方案
    Maven中xml配置文件导出到target失败问题解决方案在pom.xml中加入下面代码<!--在build中配置resources,来防止我们资源导出失败的问题--><build><resources>......
  • HTTPS解加密过程总结
    HTTPS用于解决HTTP不安全的问题。解决办法是加了一层SSL的建立过程,建立过程大概如下。1.客户端向服务器发起访问。2.服务器收到后,向CA机构发送公钥,CA机构向服务器颁发CA......
  • JSON解析器Jackson
    JSON解析器JacksonJSON解析器:常见的解析器:Jsonlib,Gson,fastjson,jacksonnjava对象转为JSON使用步骤导入jackson的相关jar包创建Jackson核心对象ObjectMapper调用ob......
  • JAVA对象与JSON转换的各种方法-fastjson
    1<!--https://mvnrepository.com/artifact/com.alibaba/fastjson-->2<dependency>3<groupId>com.alibaba</groupId>4<artifactId>fastjson</artifactId>......