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 ...
随机推荐
- 细说opcache
; opcache的开关,关闭时代码不再优化. opcache.enable=1 ; Determines if Zend OPCache is enabled for the CLI version ...
- 吴裕雄--天生自然Linux操作系统:linux yum 命令
yum( Yellow dog Updater, Modified)是一个在Fedora和RedHat以及SUSE中的Shell前端软件包管理器. 基於RPM包管理,能够从指定的服务器自动下载RPM包 ...
- 第二季第十一天 html5语义化标签 css透明度
span不能设置宽高背景 HTML5语义化标签 <section>标签所包裹的是有一组相似的主题的内容,可以用这个标签来实现文章的章节.标签式对话框中的各种标签页等类似的功能. <s ...
- keras字符编码
https://www.jianshu.com/p/258a21ae0390https://blog.csdn.net/apengpengpeng/article/details/80866034#- ...
- 用FFmpeg+nginx+rtmp搭建环境实现推流
Windows: 1.下载文件: 链接:https://pan.baidu.com/s/1c2LmIHHw-dwLOlRN6iTIMg 提取码:g7sj 2.解压文件: 解压到nginx-1.7.11 ...
- Python笔记_第四篇_高阶编程_GUI编程之Tkinter_3.数据显示
1. 表格数据显示: 图示: 实例: import tkinter from tkinter import ttk # 创建主窗口__编程头部 win = tkinter.Tk() # 设置标题 wi ...
- iOS播放器、Flutter高仿书旗小说、卡片动画、二维码扫码、菜单弹窗效果等源码
iOS精选源码 全网最详细购物车强势来袭 一款优雅易用的微型菜单弹窗(类似QQ和微信右上角弹窗) swift, UITableView的动态拖动重排CCPCellDragger 高仿书旗小说 Flut ...
- linux c 调用 so 库
/***********编译时要链接 -l dl 库************/ #include<stdlib.h> #include<stdio.h> #include< ...
- 【转】Fst指数
[转]Fst指数 转载自 http://blog.csdn.net/zhu_si_tao/article/details/71513099 与 http://blog.sina.com.cn/s/bl ...
- pyCharm专业版最新2018激活码激活
说明:本人亲测有用,对Window.Linux.Mac都稳定有效. 缺点:需要修改hosts文件 步骤: 由于管理权限问题,大部分电脑都不能直接修改hosts文件,所以我们可以先将hosts文件复制到 ...