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. 从华为数字化转型看IT自动化运维重要性

    关注嘉为科技,获取运维新知 8月有幸聆听了华为CIO陶总(陶景文)关于“华为数字化转型秘诀:坚定“以客户为中心”的思想”的演讲,获益良多.其中陶总也分享了IT运营平台的建设对于华为实现数字化转型的重要 ...

  2. nodejs安装、环境配置和测试

    nodejs下载 https://nodejs.org/en/ nodejs安装 双击下载的nodejs,可自定义安装路径,安装模块部分直接next即可安装. 检查是否安装 win+R输入cmd,打开 ...

  3. PHP策略模式demo

    <?php//策略模式就是你有很多的方法,选择一种适合自己的,// 单例模式就是只有一个实例对象,不需要每个文件都要加载,比如连接数据库,// 工厂模式就是//策略模式interface cha ...

  4. php单例模式的使用场景,使用方法

    一个类只有一个对象实例 1.含义 作为对象的创建模式,单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统全局地提供这个实例.它不会创建实例副本,而是会向单例类内部存储的实例返回一个引用. 2 ...

  5. Codefores 1151E Number of Components

    大意:给定n元素序列$a$, $1\le a_i \le n$, 定义函数$f(l,r)$表示范围在$[l,r]$以内的数构成的连通块个数, 求$\sum\limits_{i=1}^{n}\sum\l ...

  6. linux指令统计日志出现的次数

    cat  XXX.log|grep ''|grep '条件'| wc -l   单个条件统计 cat  XXX.log|grep ''|grep '条件1'|grep '条件2'|grep '条件3' ...

  7. ConcurrentHashMap1.8源码解析

    深入并发包 ConcurrentHashMap 概述 JDK1.8的实现已经摒弃了Segment的概念,而是直接用Node数组+链表+红黑树的数据结构来实现,并发控制使用Synchronized和CA ...

  8. [LeetCode] 110. Balanced Binary Tree ☆(二叉树是否平衡)

    Balanced Binary Tree [数据结构和算法]全面剖析树的各类遍历方法 描述 解析 递归分别判断每个节点的左右子树 该题是Easy的原因是该题可以很容易的想到时间复杂度为O(n^2)的方 ...

  9. 常用java命令

    javap 反编译 javap xxx.class 查看大概 javap -v -p xxx.class 查看详细 jps 查看有哪些java进程 jinfo 查看或设置java进程的 vm 参数,只 ...

  10. 码云git使用四(分支的创建,使用和合并)

    我们在使用git的时候,一般都不是直接在主代码中开发, 通常我们做的操作是创建一个分支,我们在分支上开发,开发完毕,在提交到主代码中. 我们现在学习创建分支,合并分支. 1.首先我们下载到本地都是在主 ...