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);

http发送get/post调用,传参为json对象的更多相关文章

  1. java与js交互,相互调用传参

    随着前端技术的发展与H5的广泛使用,移动端采用native+h5的方式越来越多了,对于Android来说就涉及到java与js的交互,相互调用传参等.下面就来看一下java与js交互的简单demo. ...

  2. Java项目导出为jar包+导出第三方jar包+使用命令行调用+传参

    Java项目导出为jar包+导出第三方jar包+使用命令行调用+传参 一.打包 情况1:不需要向程序传参数,并且程序没有使用第三方jar包 Eclipse上导出jar: 然后选择一个java文件作为入 ...

  3. list对象数组,xpath复杂定位校验,POST入参为number数组,POST入参为JSON对象数组

    list对象数组: POST入参为number数组: {    "typeIds":[1,2,3]} POST入参为JSON对象数组,举例: [{    "itemId& ...

  4. 发送json-简单的传参查询和简单的sql查询

    简单的传参查询并转化为json using System; using System.Collections.Generic; using System.Linq; using System.Web; ...

  5. js addEventListener调用传参函数

    先看这段代码 function abc(key){ console.log(key); } for(let i=0;i<oInput.length;i++){ oInput[i].addEven ...

  6. jQuery调用WCF服务传递JSON对象

    下面这个示例使用了WCF去创建一个服务端口从而能够被ASP.Net页面通过jQuery的AJAX方法访问,我们将在客户端使用Ajax技术来 与WCF服务进行通信.这里我们仅使用jQuery去连接Web ...

  7. shell脚本调用传参【转载】

    转自:https://www.cnblogs.com/cisum/p/8010658.html 1.直接使用$0,$1,$2,$3 $0是脚本的名字,就是按顺序来 #!/bin/bash # auth ...

  8. m 调用传参图片切换

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. bat文件中调用传参的问题

    https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-lin ...

  10. Vue使用axios请求数据,默认post请求传参是json格式,但后台需要formData格式???

    最简单的方式,post请求参数json转formData…代码如下: 使用node的 qs 模块(推荐使用) 就是这么简单,在结合element ui表单一键提交涉及到,希望遇到的同学少走弯路,加油~

随机推荐

  1. PHP:多级目录删除

    <?php // Author: windlike // Create Time: 2007-07-10 // Blog: windlike.cublog.cn function delDir( ...

  2. 用<marquee>实现图片上下滚动

    首先让我们认识这个<marquee>标签,它是成对出现的标签,首标签<marquee>和尾标签</marquee>之间的内容就是滚动内容.<marquee&g ...

  3. 使用这个model操作数据库,一爽到底

    在前一篇文章中,我们简要介绍了Vonajs的核心功能.在这里,我们再来看看Vonajs提供的Model能力,可以让我们用简洁.优雅的代码全方位操作数据库,比如,动态分表.软删除.多租户.动态数据源.二 ...

  4. div 垂直居中布局

    <div class="flex"> <div> <p>我是多行文字我是多行文字我是多行文字我是多行文字</p> <p> ...

  5. PATCH请求REST API之MyDeltas.net

    PATCH是REST API支持的请求之一. REST API的请求常见的是GET和POST,其中PUT.DELETE和PATCH也很重要. PATCH表示部分更新,用POST当然可以代替,PATCH ...

  6. 前端开发系列119-进阶篇之commonJS规范和require函数加载的过程

    今晚接到个面试电话,被问到 node中 require函数的加载过程?一两年前有研究过这部分,真的忘记了.刚刚重新调试查看了下这部分的源码,简单总结下大概的过程. 1.会默认调用require函数,其 ...

  7. 前端开发系列079-Node篇之npm+

    本文介绍NPM系列核心工具(npm.nrm.npx和nvm)的基本使用和常用的命令. 核心工具 npm(node package manager) Node的包管理工具,我们可以利用该工具来搜索.下载 ...

  8. java 中的序列化与反序列化

    简介 简单来说, java 为了在网络和硬盘上进行传输和存储进行的设计, 将一个序列化是将对象转为字节码, 然后反序列话将字节码回复成对象. 其中有一个 serialVersionUID 参数, 是为 ...

  9. leetcode 1047 双出字符串中的相邻元素

    简介 如果能想到栈的话,说明你的基础足够扎实. 我没有想到,我想到的是双向链表.我就是一个弟弟 思路 两个前后指针指向一个双向循环链表,然后判断是否相等相等的话,前一个指针前移,后一个指针后移,中间的 ...

  10. lingo 解基础 0 - 1 背包问题

    简介 没想到 0 - 1背包问题还可以这么解 question 假设现在有8件物品,他们的质量分别为3,4,6,7,9,10,11,12; 价值分别为 4,5,7,9,11,12,13,15; 假设总 ...