HttpClient 入门介绍

上一篇 / 下一篇  2012-11-23 15:04:54 / 个人分类:接口测试

1、介绍
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
HttpClient广泛应用于接口测试中。

2、使用
1)get方法
//1.创建 HttpClient 的实例
HttpClient client = new HttpClient();
//2.创建GetMethod连接方法的实例
HttpMethod method = new GetMethod("http://www.baidu.com");
try {
//3.调用executeMethod方法,该方法返回状态码,标识方法的执行结果;使用该方法需要处理2个异常
client.executeMethod(method);
//4.读取http响应
System.out.println(method.getStatusCode());
System.out.println(method.getResponseBodyAsString());
//5.释放连接
method.releaseConnection();
} catch (HttpException e) {
} catch (IOException e) {
}
运行结果:
200
<百度界面的源码>
2)post方法
HttpClient client = new HttpClient();
//client.getHostConfiguration().setHost( "www.baidu.com",80);
PostMethod post = new PostMethod("http://www.baidu.com/s");
NameValuePair value = new NameValuePair ("wd","google");
post.setRequestBody(new NameValuePair[] {value});
try {
client.executeMethod(post);
System.out.println(post.getStatusCode());
System.out.println(post.getResponseBodyAsString());
System.out.println(post.getResponseHeader("location"));
} catch (HttpException e) {
} catch (IOException e) {
}

运行结果:
302  //POST和PUT等不能自动处理转发
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="http://www.baidu.com/search/error.html">here</a>.</p>
</body></html>
Location: http://www.baidu.com/search/error.html

ps:
成功运行HttpClient需要引入3个包:
1.commons-httpclient-x.jar
2.commons-logging-x.jar
3.commons-codec-x.jar

TAG:

 

评分:0

我来说两句

Open Toolbar