1. pom.xml

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>

2. HttpClient.java

package com.midea.clean.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSONObject;
import com.midea.clean.bo.UserBo; public class HttpClient { private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class); /**
* 发送post请求
* @param url
* @param params
* @return
*/
public static String post(String url, Map<String, String> params) {
DefaultHttpClient httpclient = new DefaultHttpClient();
String body = null; HttpPost post = postForm(url, params); body = invoke(httpclient, post); httpclient.getConnectionManager().shutdown(); return body;
} /**
* 发送get请求
* @param url
* @return
*/
public static String get(String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
String body = null; HttpGet get = new HttpGet(url);
body = invoke(httpclient, get); httpclient.getConnectionManager().shutdown(); return body;
} private static String invoke(DefaultHttpClient httpclient, HttpUriRequest httpost) { HttpResponse response = sendRequest(httpclient, httpost);
String body = paseResponse(response); return body;
} private static String paseResponse(HttpResponse response) {
HttpEntity entity = response.getEntity(); String charset = EntityUtils.getContentCharSet(entity); String body = null;
try {
body = EntityUtils.toString(entity);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} return body;
} private static HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost) {
HttpResponse response = null; try {
response = httpclient.execute(httpost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
} private static HttpPost postForm(String url, Map<String, String> params) { HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
// 需要传一个token
//httpost.setHeader("token", "c7a4e021-6527-11e6-96be-fcaa14c3021a1");
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
} try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} return httpost;
} /**
* post方式提交json代码
* @throws Exception
*/
public static String postJson(String url,String json) throws Exception{
//创建默认的httpClient实例.
CloseableHttpClient httpclient = null;
//接收响应结果
CloseableHttpResponse response = null;
String result = "";
//创建httppost
httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json");
//参数
StringEntity se = new StringEntity(json);
se.setContentEncoding("UTF-8");
se.setContentType("application/json");//发送json需要设置contentType
httpPost.setEntity(se);
LOGGER.debug("http post url:{},json:{}",url,json);
response = httpclient.execute(httpPost);
LOGGER.debug("http post result:{}", response);
//解析返结果
HttpEntity entity = response.getEntity();
if(entity != null){
result = EntityUtils.toString(entity, "UTF-8");
}
httpclient.close();
response.close();
return result;
} public static void main(String[] args) throws Exception {
// HttpClient.get("http://localhost/clean/4a/welcome"); // Map<String,String> params = new HashMap<String,String>();
// params.put("empName", "1");
// params.put("empCode", "2");
// HttpClient.post("http://localhost/clean/4a/privilege/check", params); UserBo userBo = new UserBo();
userBo.setEmpCode("3");
userBo.setEmpName("zs");
userBo.setErpUid("4");
userBo.setMip("5");
String jsonStr = JSONObject.toJSONString(userBo); HttpClient.postJson("http://localhost/clean/4a/privilege/check", jsonStr);
} }

  

org.apache.httpcomponents httpclient 发起HTTP JSON请求的更多相关文章

  1. httpclient工具使用(org.apache.httpcomponents.httpclient)

    httpclient工具使用(org.apache.httpcomponents.httpclient) 引入依赖 <dependency> <groupId>org.apac ...

  2. org.apache.httpcomponents.httpclient

    apache org doc :http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e49 ...

  3. Java使用Apache的HttpClient组件发送https请求

    如果我们直接通过普通的方式对https的链接发送请求,会报一个如下的错误: javax.net.ssl.SSLHandshakeException: sun.security.validator.Va ...

  4. HttpClient发起Http/Https请求工具类

    <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcl ...

  5. org.apache.httpcomponents:httpclient 工具类

    基于httpclient 版本4.4.1 因为http连接需要三次握手,在需要频繁调用时浪费资源和时间 故采用连接池的方式连接 根据实际需要更改  连接池最大连接数.路由最大连接数 另一个需要注意的是 ...

  6. Apache HttpComponents 通过代理发送HTTP请求

    package org.apache.http.examples.client; import org.apache.http.HttpEntity; import org.apache.http.H ...

  7. JAVA中使用Apache HttpComponents Client的进行GET/POST请求使用案例

    一.简述需求 平时我们需要在JAVA中进行GET.POST.PUT.DELETE等请求时,使用第三方jar包会比较简单.常用的工具包有: 1.https://github.com/kevinsawic ...

  8. org.apache.commons.httpclient工具类

    import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpcl ...

  9. org.apache.commons.httpclient工具类(封装的HttpUtil)

    import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java ...

随机推荐

  1. Setting up a Hadoop cluster - Part 1: Manual Installation

    http://gbif.blogspot.com/2011/01/setting-up-hadoop-cluster-part-1-manual.html

  2. android -------- ConstraintLayout Guideline和Barrier(四)

    前面的文章 ConstraintLayout 介绍 (一) ConstraintLayout约束属性 (二) ConstraintLayout 宽高比和偏移量比(三) 此博文主要讲解:Guidelin ...

  3. python记录_day03 字符串

    python基本数据类型回顾 1. int 整数 2. str 字符串. 不会用字符串保存大量的数据 3. bool 布尔值. True, False 4. list 列表(重点) 存放大量的数据 5 ...

  4. 第一阶段——站立会议总结DAY04

    1.昨天做了什么:未取得一点进步. 2.今天准备做什么:准备在网上搜索一下微信个人中心的相关信息,代码资料. 3.遇到的困难:界面简陋,还是对于深层次的,比如逻辑,还是不怎么会用.

  5. Matlab-11:Gausssidel迭代法工具箱

    算法推导: function [u,n]=GaussSeid(A,b,u0,eps,M) %GaussSeid.m为用高斯-塞德尔迭代法求解线性方程组 %A为线性方程组的系数矩阵 %b为线性方程组的常 ...

  6. java之collection总结

    Collection 来源于Java.util包,是非常实用常用的数据结构!!!!!字面意思就是容器.具体的继承实现关系如下图,先整体有个印象,再依次介绍各个部分的方法,注意事项,以及应用场景.   ...

  7. P2756 飞行员配对方案问题

    题目背景 第二次世界大战时期.. 题目描述 英国皇家空军从沦陷国征募了大量外籍飞行员.由皇家空军派出的每一架飞机都需要配备在航行技能和语言上能互相配合的2 名飞行员,其中1 名是英国飞行员,另1名是外 ...

  8. Leetcode 1013. 总持续时间可被 60 整除的歌曲

    1013. 总持续时间可被 60 整除的歌曲  显示英文描述 我的提交返回竞赛   用户通过次数450 用户尝试次数595 通过次数456 提交次数1236 题目难度Easy 在歌曲列表中,第 i 首 ...

  9. MinGW安装教程( MinGW - Minimalist GNU for Windows)

    首先说明一下 1) MinGw只是其中一种GCC编译环境的安装程序,还有像Cygwin也是差不多的; 2) 还要就是安装MinGw,最好在一个网络比较好的环境中进行,  (有可能导致后来安装其他软件像 ...

  10. 使用iText快速更新书签

    一.介绍 pdfbox基于Apache协议,商用无需开放源代码. iText基于APGL协议,打包和修改需发布源码,除非花钱买断. 二.用途 下载的电子书,有的书签是FitHeight,也就是缩放后整 ...