HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。当前官网最新版介绍页是:http://hc.apache.org/httpcomponents-client-4.5.x/index.html

许多模拟http请求的框架都用httpclient,测试人员可通过它模拟请求http协议接口,做接口自动化测试。

1、包下载:
地址:http://mvnrepository.com/

        <!-- maven依赖 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>

发送get请求

1、通过请求参数url和头文件cookie作为参数(cookie可以为空)发送get请求,读取返回内容

代码如下:

public static String httpGet(String url,String cookie) throws Exception{  

        String result=""; //返回信息
//创建一个httpGet请求
HttpGet request=new HttpGet(url);
//创建一个htt客户端
@SuppressWarnings("resource")
HttpClient httpClient=new DefaultHttpClient();
//添加cookie到头文件
request.addHeader("Cookie", cookie);
//接受客户端发回的响应
HttpResponse httpResponse=httpClient.execute(request);
//获取返回状态
int statusCode=httpResponse.getStatusLine().getStatusCode();
if(statusCode==HttpStatus.SC_OK){
//得到客户段响应的实体内容
HttpEntity responseHttpEntity=httpResponse.getEntity();
//得到输入流
InputStream in=responseHttpEntity.getContent();
//得到输入流的内容
result=getData(in);
}
//Log.d(TAG, statusCode+"");
return result;
}

2、有时候,当我们想获取返回头文件信息,而不是返回内容时,只需要修改:

      //获取返回状态
int statusCode=httpResponse.getStatusLine().getStatusCode();
if(statusCode==HttpStatus.SC_OK){
//取头文件名(header值)信息
strResult=httpResponse.getHeaders(header)[0].getValue().toString();
// Header[] headers = httpResponse.getAllHeaders();//返回的HTTP头信息
// for (int i=0; i<headers.length; i++) {
// System.out.println(headers[i]);
// }
}

发送post请求

1、请求地址、请求参数(map格式)、请求cookie作为参数发送Post请求

public static String httpPost(String url,Map<String,String> map,String cookie) {
//返回body
String body = "";
//1、创建一个htt客户端
@SuppressWarnings("resource")
HttpClient httpClient=new DefaultHttpClient();
//2、创建一个HttpPost请求
HttpPost response=new HttpPost(url); //3、设置参数
//建立一个NameValuePair数组,用于存储欲传送的参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
if(map!=null){
for (Entry<String, String> entry : map.entrySet()) {
//添加参数
params.add( new BasicNameValuePair(entry.getKey(),entry.getValue()) );
}
} //4、设置参数到请求对象中
try {
response.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} //5、设置header信息
response.setHeader("Content-type", "application/x-www-form-urlencoded");
response.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//添加cookie到头文件
response.addHeader("Cookie", cookie); //6、设置编码
//response.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//7、执行post请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse httpResponse;
try {
httpResponse = (CloseableHttpResponse) httpClient.execute(response);
//获取结果实体
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
//释放链接
httpResponse.close();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return body;
}

2、post请求获取头文件header信息

//7执行post请求
HttpResponse response = httpClient.execute(httpPost);
//取头信息
Header[] headers = response.getAllHeaders();
for(int i=0;i<headers.length;i++) {
System.out.println(headers[i].getName() +"=="+ headers[i].getValue());
}

3、addHeader与setHeader区别

HttpClient在添加头文件的时候,需要用到addHeader或setHeader

区别:

1、同名Header可以有多个 ,Header[] getHeaders(String name)。
2、运行时使用的是第一个, Header getFirstHeader(String name)。
3、addHeader,如果同名header已存在,则追加至原同名header后面。
4、setHeader,如果同名header已存在,则覆盖一个同名header。

2、源代码

链接:http://files.cnblogs.com/files/airsen/HttpClientUtil.rar

参考

1、httpclient中文翻译:http://blog.csdn.net/column/details/httpclient.html

2、httpclient翻译:http://blog.csdn.net/linghu_java/article/details/43306613

3、轻松把玩HttpClient之模拟post请求示例:http://blog.csdn.net/xiaoxian8023/article/details/49863967

4、http://www.codeweblog.com/httpclient-%E6%93%8D%E4%BD%9C%E5%B7%A5%E5%85%B7%E7%B1%BB/

使用httpclient发送get或post请求的更多相关文章

  1. HttpClient发送get,post接口请求

    HttpClient发送get post接口请求/*  * post  * @param url POST地址 * @param data POST数据NameValuePair[] * @retur ...

  2. Android笔记---使用HttpClient发送POST和GET请求

    在Android上发送 HTTP 请求的方式一般有两种, HttpURLConnection 和 HttpClient,关于HttpURLConnection的使用方法能够參考HTTP之利用HttpU ...

  3. Java实现HttpClient发送GET、POST请求(https、http)

    1.引入相关依赖包 jar包下载:httpcore4.5.5.jar    fastjson-1.2.47.jar maven: <dependency> <groupId>o ...

  4. HttpClient发送Get和Post请求

    package JanGin.httpClient.demo; import java.io.IOException; import java.io.UnsupportedEncodingExcept ...

  5. HttpClient 发送 HTTP、HTTPS 请求的简单封装

    import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.Http ...

  6. [java,2018-01-16] HttpClient发送、接收 json 请求

    最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据. 就抽取出来写了一个帮助类: 首先判断发送的数据类型是json还是xml: import org.dom4j.Do ...

  7. 读取配置文件的URL,使用httpClient发送Post和Get请求,实现查询快递物流和智能机器人对话

    1.主要jar包: httpclient-4.3.5.jar   httpcore-4.3.2.jar 2.目录结构如图所示: 3.url.properties文件如下: geturl=http:// ...

  8. 【httpclient-4.3.1.jar】httpclient发送get、post请求以及携带数据上传文件

    1.发送get.post携带参数以及post请求接受JSON数据: package cn.qlq.utils; import java.io.BufferedReader; import java.i ...

  9. java使用HttpClient 发送get、pot请求

    package eidolon.messageback.PostUtil; import java.io.BufferedReader; import java.io.IOException; imp ...

随机推荐

  1. 【Win 10应用开发】在RichEditBox中使用自定义菜单

    前面给大伙儿简单介绍了RichEditBox控件的基本用法,以及解决其中的一些小问题. 本文咱们来看看如何自定义RichEditBox控件的上下文菜单. 原理比较简单,所以先说一说原理.当RichEd ...

  2. STL标准模板库(简介)

    标准模板库(STL,Standard Template Library)是C++标准库的重要组成部分,包含了诸多在计算机科学领域里所常见的基本数据结构和基本算法,为广大C++程序员提供了一个可扩展的应 ...

  3. Android ButterKnife配置使用

    ButterKnife在GitHub的地址:https://github.com/JakeWharton/butterknife 最新的版本是:8.4.0 app 模块的build.gradle: a ...

  4. jQuery -原生 如何互转

    今天研究源码的时候发现,不需要用get() 也能进行原生转换,使用原生方法. 原生- jQuery对象   var obj=document.xxx $(obj).css(); 也可以直接 $(doc ...

  5. Hibernate(5)—— 联合主键 、一对一关联关系映射(xml和注解) 和 领域驱动设计

    俗话说,自己写的代码,6个月后也是别人的代码……复习!复习!复习!涉及的知识点总结如下: One to One 映射关系 一对一单向外键(XML/Annotation) 一对一双向外键关联(XML/A ...

  6. 【NLP】Python NLTK 走进大秦帝国

    Python NLTK 走进大秦帝国 作者:白宁超 2016年10月17日18:54:10 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集的大量公 ...

  7. Java Map hashCode深究

    [Java心得总结七]Java容器下——Map 在自己总结的这篇文章中有提到hashCode,但是没有细究,今天细究整理一下hashCode相关问题 1.hashCode与equals 首先我们都知道 ...

  8. Vertica DBD 分析优化设计

    DBD = Database Designer,是Vertica数据库优化中最主要的原生工具. 首先运行admintools工具,按下面步骤依次执行: 1.选择"6 Configuratio ...

  9. Error:const char* 类型的实参和LPCWSTR类型的形参不兼容的解决方法。

    在C++的Windows 应用程序中经常碰到这种情况. 解决方法: 加入如下转换函数: LPCWSTR stringToLPCWSTR(std::string orig) { size_t origs ...

  10. 【小型系统】简单的刷票系统(突破IP限制进行投票)

    一.前言 相信大家平时肯定会收到朋友发来的链接,打开一看,哦,需要投票.投完票后弹出一个页面(恭喜您,您已经投票成功),再次点击的时候发现,啊哈,您的IP(***.***.***.***)已经投过票了 ...