Java发送Post请求,参数JSON,接收JSON
/**
* 发送post请求
* @param url 路径
* @param jsonObject 参数(json类型)
* @param encoding 编码格式
* @return
* @throws ParseException
* @throws IOException
*/
public static String send(String url, JSONObject jsonObject,String encoding) throws ParseException, IOException{
String body = ""; //创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url); //装填参数
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
//设置参数到请求对象中
httpPost.setEntity(s);
System.out.println("请求地址:"+url);
// System.out.println("请求参数:"+nvps.toString()); //设置header信息
//指定报文头【Content-type】、【User-Agent】
// httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}
下面代码自己写。
2019/11/18,看到代码挺多人看的,再给大家提供一个Http工具类,数据提交包括 Raw,Json等
package com.xiaojiang.checkin.utils; import com.alibaba.fastjson.JSONObject;
import com.xiaojiang.checkin.entity.HttpClientResult;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.*; /**
* Description: httpClient工具类
*
* @author JourWon
* @date Created on 2018年4月19日
*/
public class HttpClientUtils { // 编码格式。发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8"; // 设置连接超时时间,单位毫秒。
private static final int CONNECT_TIMEOUT = 6000; // 请求获取数据的超时时间(即响应时间),单位毫秒。
private static final int SOCKET_TIMEOUT = 6000; /**
* 发送get请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url) throws Exception {
return doGet(url, null, null);
} /**
* 发送get请求;带请求参数
*
* @param url 请求地址
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
return doGet(url, null, params);
} /**
* 发送get请求;带请求头和请求参数
*
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建访问的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
} // 创建http对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig); // 设置请求头
packageHeader(headers, httpGet); // 创建httpResponse对象
CloseableHttpResponse httpResponse = null; try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpGet);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
} /**
* 发送post请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url) throws Exception {
return doPost(url, null, null);
} /**
* 发送post请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
return doPost(url, null, params);
} /**
* 发送post请求;带请求头和请求参数
*可发送Formdata数据,请把请求头设置一下,不然获取不到数据。
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建http对象
HttpPost httpPost = new HttpPost(url);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 设置请求头
/*httpPost.setHeader("Cookie", "");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
packageHeader(headers, httpPost); // 封装请求参数
packageParam(params, httpPost); // 创建httpResponse对象
CloseableHttpResponse httpResponse = null; try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
} /***
* 发送post请求封装formdata
*
*/ // public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params){
//
// } /**
* 发送POST请求带Raw参数
* */
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params,String raw) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建http对象
HttpPost httpPost = new HttpPost(url);
//封装raw 参数
packageRaw(raw,httpPost);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 设置请求头
/*httpPost.setHeader("Cookie", "");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
packageHeader(headers, httpPost); // 封装请求参数
packageParam(params, httpPost); // 创建httpResponse对象
CloseableHttpResponse httpResponse = null; try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
} /***
* 发送Post有些这封装代码
* 封装formdata数据
*/
public static void packageFormData(Map<String,String> params,HttpEntityEnclosingRequestBase HttpMethod){
List<NameValuePair> paramList = new ArrayList <NameValuePair>();
if(params != null && params.size() > 0){
Set<String> keySet = params.keySet();
for(String key : keySet) {
paramList.add(new BasicNameValuePair(key, params.get(key)));
}
}
HttpMethod.setEntity(new UrlEncodedFormEntity(paramList,Charset.forName("UTF-8")));
System.out.println(paramList);
} /**
* 封装Raw数据
* */
public static void packageRaw(String raw,HttpEntityEnclosingRequestBase HttpMethod){
try {
//传map进来需要自己封装key,val
StringEntity postingString = new StringEntity(raw);// json传递
HttpMethod.setEntity(postingString);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} } /**
* 发送put请求;不带请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url) throws Exception {
return doPut(url);
} /**
* 发送put请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig); packageParam(params, httpPut); CloseableHttpResponse httpResponse = null; try {
return getHttpClientResult(httpResponse, httpClient, httpPut);
} finally {
release(httpResponse, httpClient);
}
} /**
* 发送delete请求;不带请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpDelete.setConfig(requestConfig); CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpDelete);
} finally {
release(httpResponse, httpClient);
}
} /**
* 发送delete请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
if (params == null) {
params = new HashMap<String, String>();
} params.put("_method", "delete");
return doPost(url, params);
} /**
* Description: 封装请求头
* @param params
* @param httpMethod
*/
public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封装请求头
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
// 设置到请求头到HttpRequestBase对象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
} /**
* Description: 封装请求参数
*
* @param params
* @param httpMethod
* @throws UnsupportedEncodingException
*/
public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
// 封装请求参数
if (params != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
} // 设置到请求的http对象中
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
} /**
* Description: 获得响应结果
*
* @param httpResponse
* @param httpClient
* @param httpMethod
* @return
* @throws Exception
*/
public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
// 执行请求
httpResponse = httpClient.execute(httpMethod);
// 获取返回结果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
}
return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(),content);
}
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} /**
* Description: 释放资源
*
* @param httpResponse
* @param httpClient
* @throws IOException
*/
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
} }
Java发送Post请求,参数JSON,接收JSON的更多相关文章
- ExtJS发送POST请求 参数格式为JSON
背景 这要从我比较懒说起.技术框架ExtJS + resteasy,默认请求方式是ajax get,这后台方法就要写很多@QueryParam来获取参数.我比较喜欢前台用ajax post请求,后台方 ...
- java 发送post请求参数中含有+会转化为空格的问题
如题 原因分析:参数在传递过程中经历的几次编码和解码标准不同,导致加号.空格等字符的错误. 解决方案:将post请求的参数中 ,含有+号的,统统采用%2B 去替换,这是URL的协议问题.
- 我的Android进阶之旅------>android如何将List请求参数列表转换为json格式
本文同步发表在简书,链接:http://www.jianshu.com/p/395a4c8b05b9 前言 由于接收原来的老项目并进行维护,之前的http请求是使用Apache Jakarta Com ...
- andlua,andlua发送http请求,并解析json数据
andlua发送http请求,并解析json实例 import'cjson'import 'http'--导入cjson库url = 'https://www.baidu,com'--设置urlHtt ...
- Java发送Http请求并获取状态码
通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...
- Java发送HTTPS请求
前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊, ...
- Jquery Datatables 请求参数及接收参数处理
Jquery Datatables 请求参数及接收参数处理 /** * Created by wb-wuyifu on 2016/8/9. */ /** * Created by wb-wuyifu ...
- 通过java发送http请求
通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...
- 使用Java发送Http请求的内容
公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容.这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过. 学习了J ...
随机推荐
- 系统学习python第五天学习笔记
1.列表补充 extend() li = ["alex", "WuSir", "ritian", "barry", &q ...
- 67)vector的begin() end() 和 front() back()的区别 rbegin() rend()
1) ·············· 2)`````````v1.begin() 和v1.end() 是作为迭代器v1的 第一个位置 和 最后一个元素的下一个位置. `````````````v1. ...
- storm 机制
storm基础系列之二----zookeeper的作用 https://www.cnblogs.com/xyang/p/5643745.html Zookeeper+Storm集群搭建 https:/ ...
- JS—DOM操作
节点分为三类: 1.元素节点:标签<div></div> 2.文本节点:标签内的纯文本. 3.属性节点:标签内的属性,id或class 查找元素: getElementById ...
- IntelliJ IDEA 2019.2 LUA环境搭建说明
1.搭建GCC 添加系统环境变量PATH 为C:\MinGW\bin目录 测试命令进入CMD gcc -v 2.编译LUA cd到lua/src目录 mingw32-make min ...
- [原]调试实战——使用windbg调试DLL卸载时的死锁
原调试debugwindbg死锁deadlock 前言 最近我们的程序在退出时会卡住,调查发现是在卸载dll时死锁了.大概流程是这样的:我们的dll在加载的时候会创建一个工作线程,在卸载的时候,会设置 ...
- Methyl-SeqDNA的甲基化图谱|DNase I-Seq|ChIP-Seq|3C-Seq|
生物医学大数据 Methyl-SeqDNA的甲基化图谱 DNase I-Seq全基因组染色质DNA的开放程度.非基因编码区的调控元件的分布 DNase I高敏感位点:基因处于转录活性状态时,其染色质结 ...
- CF633H Fibonacci-ish II(莫队+线段树)
温馨提示:本题十分卡常数,我手动开O2才过的.而数据范围不伦不类的n<=30000,常数小的O(n2)居然比O(n√nlogn)跑得快…… 考虑插进去一个元素对答案产生的影响.原本数列为Σa[i ...
- HDU - 1754 线段树
#include <algorithm> #include <iostream> #include<sstream> #include<cstring> ...
- 如何选择开源项目的license
https://choosealicense.com/ http://www.csdn.net/article/2013-07-16/2816249-Github-Open-Source-Licens ...