使用httpclient发送get或post请求
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请求的更多相关文章
- HttpClient发送get,post接口请求
HttpClient发送get post接口请求/* * post * @param url POST地址 * @param data POST数据NameValuePair[] * @retur ...
- Android笔记---使用HttpClient发送POST和GET请求
在Android上发送 HTTP 请求的方式一般有两种, HttpURLConnection 和 HttpClient,关于HttpURLConnection的使用方法能够參考HTTP之利用HttpU ...
- Java实现HttpClient发送GET、POST请求(https、http)
1.引入相关依赖包 jar包下载:httpcore4.5.5.jar fastjson-1.2.47.jar maven: <dependency> <groupId>o ...
- HttpClient发送Get和Post请求
package JanGin.httpClient.demo; import java.io.IOException; import java.io.UnsupportedEncodingExcept ...
- HttpClient 发送 HTTP、HTTPS 请求的简单封装
import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.Http ...
- [java,2018-01-16] HttpClient发送、接收 json 请求
最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据. 就抽取出来写了一个帮助类: 首先判断发送的数据类型是json还是xml: import org.dom4j.Do ...
- 读取配置文件的URL,使用httpClient发送Post和Get请求,实现查询快递物流和智能机器人对话
1.主要jar包: httpclient-4.3.5.jar httpcore-4.3.2.jar 2.目录结构如图所示: 3.url.properties文件如下: geturl=http:// ...
- 【httpclient-4.3.1.jar】httpclient发送get、post请求以及携带数据上传文件
1.发送get.post携带参数以及post请求接受JSON数据: package cn.qlq.utils; import java.io.BufferedReader; import java.i ...
- java使用HttpClient 发送get、pot请求
package eidolon.messageback.PostUtil; import java.io.BufferedReader; import java.io.IOException; imp ...
随机推荐
- 初学者--bootstrap(六)组件中的下拉菜单----在路上(10)
组件---下拉菜单 用于显示链接列表的可切换.有上下文的菜单.下拉菜单的 JavaScript 插件让它具有了交互性. 将下拉菜单触发器和下拉菜单都包裹在 .dropdown 里,或者另一个声明了 p ...
- Jps命令—使用详解
jps是jdk提供的一个查看当前Java进程的小工具, 可以看做是JavaVirtual Machine Process Status Tool的缩写.非常简单实用. 命令格式:jps [option ...
- 图片在保存的时候===》出现这个异常:GDI+ 中发生一般性错误
异常处理汇总-后端系列 http://www.cnblogs.com/dunitian/p/4523006.html 一般这种情况都是没有权限,比如目录没有创建就写入,或者没有写入文件的权限 我的是目 ...
- SQL Server 批量主分区备份(One Job)
一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 案例分析(Case) 实现代码(SQL Codes) 主分区完整.差异还原(Primary B ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(29)-T4模版
系列目录 本节不再适合本系统,在58,59节已经重构.请超过本节 这讲适合所有的MVC程序 很荣幸,我们的系统有了体验的地址了.演示地址 之前我们发布了一个简单的代码生成器,其原理就是读取数据库的表结 ...
- Encountered an unexpected error when attempting to resolve tag helper directive '@addTagHelper' with value '"*, Microsoft.AspNet.Mvc.TagHelpers"'
project.json 配置: { "version": "1.0.0-*", "compilationOptions": { " ...
- JS 对象封装的常用方式
JS是一门面向对象语言,其对象是用prototype属性来模拟的,下面,来看看如何封装JS对象. 常规封装 function Person (name,age,sex){ this.name = na ...
- Vertica 6.1不完全恢复启动到LGE方法
环境:RHEL6.2 + Vertica 6.1.3-7 确定所有节点的vertica进程都停掉(包括agent和python),如果有运行的,停止它或者杀掉它. 确定所有节点的spread进程都正常 ...
- Discuz X3.2 网站快照被劫持的解决方法
附上另一个人的解决方法:http://www.discuz.net/thread-3549930-3-1.html 问题如下: 快照被劫持,无论怎么申诉,怎么更新快照,都无法消除此问题,第一次打开网站 ...
- 通过pycharm使用git[图文详解]
前言 使用git+pycharm有一段时间了,算是稍有点心得,这边整理一下,可能有的方法不是最优,欢迎交流,可能还是习惯敲命令去使用git,不过其实pycharm已经帮忙做了很多了,我们可以不用记住那 ...