什么是httpclient
  HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
下载地址:http://hc.apache.org/
使用范例

public class HttpClientTest {
@Test
public void doGet() throws Exception {
//创建一个httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个GET对象
HttpGet get = new HttpGet("http://www.sogou.com");
//执行请求
CloseableHttpResponse response = httpClient.execute(get);
//取响应的结果
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);//返回200
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);//返回sogou主页的页面代码
//关闭httpclient
response.close();
httpClient.close();
}
@Test
public void doGetWithParam() throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个uri对象
URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
uriBuilder.addParameter("query", "花千骨");
HttpGet get = new HttpGet(uriBuilder.build());
CloseableHttpResponse response = httpClient.execute(get);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
response.close();
httpClient.close();
}
@Test
public void doPost() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个post对象
HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.action");
//执行post请求
CloseableHttpResponse response = httpClient.execute(post);
String string = EntityUtils.toString(response.getEntity());
System.out.println(string);
response.close();
httpClient.close();
}
@Test
public void doPostWithParam() throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个post对象
HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.action");
//创建一个Entity。模拟一个表单
List<NameValuePair> kvList = new ArrayList<>();
kvList.add(new BasicNameValuePair("username", "张三"));
kvList.add(new BasicNameValuePair("password", "123"));
//包装成一个Entity对象
StringEntity entity = new UrlEncodedFormEntity(kvList, "utf-8");
//设置请求的内容
post.setEntity(entity);
//执行post请求
CloseableHttpResponse response = httpClient.execute(post);
String string = EntityUtils.toString(response.getEntity());
System.out.println(string);
response.close();
httpClient.close();
}
}

 封装工具类

public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}

HttpClientUtil

httpclient介绍与使用的更多相关文章

  1. HttpClient介绍和使用

    HttpClient介绍和使用 今天有一个需求:后台访问一个接口,获取返回的数据.于是找到了HttpClient 1.介绍 SpringCloud中服务和服务之间的调用全部是使用HttpClient, ...

  2. 接口测试——httpclient介绍与请求方式详解

    httpClient工具介绍 HTTP协议可能是现在lntemet上使用得最多.最重要的协议了,越来越多的Java应用程序需要直接通过HTTP协议来访问网络资源.虽然在JDK的java.net包中已经 ...

  3. httpclient介绍与请求方式详解

    httpClient工具介绍 HTTP协议可能是现在lntemet上使用得最多.最重要的协议了,越来越多的Java应用程序需要直接通过HTTP协议来访问网络资源.虽然在JDK的java.net包中已经 ...

  4. httpclient介绍

    前言 超文本传输协议(HTTP)也许是当今互联网上使用的最重要的协议了.Web服务,有网络功能的设备和网络计算的发展,都持续扩展了HTTP协议的角色,超越了用户使用的Web浏览器范畴,同时,也增加了需 ...

  5. HttpClient介绍和简单使用流程

    HttpClient SpringCloud中服务和服务之间的调用全部是使用HttpClient,还有前面使用SolrJ中就封装了HttpClient,在调用SolrTemplate的saveBean ...

  6. 【JAVA】通过HttpClient发送HTTP请求的方法

    HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 ...

  7. 理解并使用.NET 4.5中的HttpClient

    HttpClient介绍 HttpClient是.NET4.5引入的一个HTTP客户端库,其命名空间为System.Net.Http..NET 4.5之前我们可能使用WebClient和HttpWeb ...

  8. Android入门:用HttpClient模拟HTTP的GET和POST请求

    一.HttpClient介绍   HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器:   Android已经集成了HttpClient,因此可以直接使用: ...

  9. HttpClient中异步方法的同步调用

    在System.Net.Http中,提供了使用Http与远程服务器通讯的httpClient,但是里面都是异步方法,有时候我们并不需要使用异步操作.这个时候可以使用如下的方式来进行同步调用. clas ...

随机推荐

  1. AngularJS table 按照表头字段排序功能(升序和降序)

    一.表格按照表头排序 <!doctype html> <html ng-app="a3_4"> <head> <title>表头排序 ...

  2. js 事件委托代理

    在优化网页性能的技巧当中,对DOM的优化是必不可少的.这其中就涉及到了javascript对DOM的频繁操作.比如响应用户操作的事件.一般情况下,如果是稍微初级一点的前端程序员,在拿到项目的时候,对待 ...

  3. Leaflet.draw 无法编辑multipolygon类型多边形 解决方法

    问题说明 在做面要素的编辑的时候,当对multiploygon类型的面要素进行编辑的时候,出现如下错误: TypeError: Cannot read property 'lat' of null 通 ...

  4. 在JavaScript文件中用jQuery方法实现日期时间选择功能

    JavaScript Document $(document).ready(function(e) { 在文本框里面显示当前日期 var date = new Date(); var nian = d ...

  5. android-studio开发NDK错误记录:bash: ../../build/intermediates/classes/debug: is a directory

    按照网上很多已有的教程,在用javah生成c的头文件时候报错: Error: no classes specified bash: ../../build/intermediates/classes/ ...

  6. Google 和 Facebook 如何大规模处理 IT 事件管理 —— 2016 SRE 大会之我见

    [编者按]本文作者为 Maria Arbisman,主要介绍 Google 与 Facebook 两大巨头是如何大规模处理 IT 事件管理.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 2 ...

  7. AWS CSAA -- 04 AWS Object Storage and CDN - S3 Glacier and CloudFront(一)

    013 S3 - 101 014 Create an S3 Bucket - Lab

  8. 使用FireFox插件RESTClient、HttpRequester模拟http(get post)请求

    我们写好一个接口后,需要进行测试.有时我们会写一个html表单提交,无疑增加了工作量,尤其是当参数比较多或者传json或xml数据时,效率更是大大降低.我们可以使用基于FireFox的RESTClie ...

  9. 关于 Azure Windows VM 的磁盘和 VHD

    就像其他任何计算机一样,Azure 中的虚拟机将磁盘用作存储操作系统.应用程序和数据的位置. 所有 Azure 虚拟机都至少有两个磁盘,即 Windows 操作系统磁盘和临时磁盘. 操作系统磁盘基于映 ...

  10. Azure 中的 Windows 虚拟机概述

    Azure 虚拟机 (VM) 是 Azure 提供的多种可缩放按需分配计算资源之一. 通常情况下,如果需要以更大的力度(相对于其他控制选项)控制计算环境,则应选择 VM. 本文介绍创建 VM 之前的注 ...