/**
* 发送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的更多相关文章

  1. ExtJS发送POST请求 参数格式为JSON

    背景 这要从我比较懒说起.技术框架ExtJS + resteasy,默认请求方式是ajax get,这后台方法就要写很多@QueryParam来获取参数.我比较喜欢前台用ajax post请求,后台方 ...

  2. java 发送post请求参数中含有+会转化为空格的问题

    如题 原因分析:参数在传递过程中经历的几次编码和解码标准不同,导致加号.空格等字符的错误. 解决方案:将post请求的参数中 ,含有+号的,统统采用%2B 去替换,这是URL的协议问题.

  3. 我的Android进阶之旅------>android如何将List请求参数列表转换为json格式

    本文同步发表在简书,链接:http://www.jianshu.com/p/395a4c8b05b9 前言 由于接收原来的老项目并进行维护,之前的http请求是使用Apache Jakarta Com ...

  4. andlua,andlua发送http请求,并解析json数据

    andlua发送http请求,并解析json实例 import'cjson'import 'http'--导入cjson库url = 'https://www.baidu,com'--设置urlHtt ...

  5. Java发送Http请求并获取状态码

    通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...

  6. Java发送HTTPS请求

    前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊, ...

  7. Jquery Datatables 请求参数及接收参数处理

    Jquery Datatables 请求参数及接收参数处理 /** * Created by wb-wuyifu on 2016/8/9. */ /** * Created by wb-wuyifu ...

  8. 通过java发送http请求

    通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...

  9. 使用Java发送Http请求的内容

    公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容.这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过. 学习了J ...

随机推荐

  1. 设计模式讲解2:static proxy和decorator的不同点

    声明:迁移自本人CSDN博客https://blog.csdn.net/u013365635 在常见的23种设计模式中,static proxy和decorator在代码结构上是特别相似的.那它们的不 ...

  2. 17.3.12--time模块

    import time  #导入time模块 应用的时候有两种方式来表示时间: 1)时间戳 2)格式化的时间str(字符串)   3)元祖(struct_time)以及calendar 2---tim ...

  3. Properties in Algebra

    附录-Properties in Algebra 部分证明转载自标注,仅作个人整理查阅用. 范数 (norm) \(^{[1]}\) 要更好的理解范数,就要从函数.几何与矩阵的角度去理解,我尽量讲的通 ...

  4. CF809C(找规律+数位DP)

    老年选手需要多写一些思维题qwq. 通过打表很容易发现对于(i,j),值为(i-1)^(j-1)+1,然后本题就没了qwq. 矩阵差分还是很容易想到的,容斥成四个矩阵. 然后看到异或很容易想到三件事: ...

  5. <强化学习>开门帖

    (本系列只用作本人笔记,如果看官是以新手开始学习RL,不建议看我写的笔记昂) 今天是2020年2月7日,开始二刷david silver ulc课程.https://www.youtube.com/w ...

  6. HTTP Error 502.5 - Process Failure 解决方案

    .netcore 2.1.4的程序部署到IIS后报以下错误: ======================================================= HTTP Error 50 ...

  7. mysql数据库5.6.45安装后的配置(离线安装包版)

    二.windows10下的配置 (1) 环境变量配置 打开控制面板=>系统和安全=>系统=>高级系统设置,选择环境变量,在系统变量中找到path,编辑该选项. 第一行是oracle数 ...

  8. PCoA|NMDS|STRESS|RDA |RA|Unimodal|CCA|Generalized Joint Attribute Modeling

    PCoA:主坐标轴分析 数值型变量使用各种距离公式,而分类变量看是否相同,比如, Aabbcc || Aaffff 其中,两个相同,4个不同,一组6个,则(6+6-2*2)=8. PC0A与PCA区别 ...

  9. Educational Codeforces Round 66 差G

    Educational Codeforces Round 66 F 题意:长度为 n 的序列,求有多少个区间 \([l,r]\) ,使得其构成了一个 1~r-l+1 的排列. \(n \le 3*10 ...

  10. WMS备货单保存后自动新增选项不勾选