HttpClint基本介绍
- 超文本传输协议(HTTP)可能是当今Internet上使用的最重要的协议。
- Web服务,支持网络的设备和网络计算的发展继续将HTTP协议的作用扩展到用户驱动的Web浏览器之外,同时增加了需要HTTP支持的应用程序的数量。
- 尽管java.net包提供了通过HTTP访问资源的基本功能,但它并未提供许多应用程序所需的完全灵活性或功能。HttpClient旨在通过提供一个高效,最新且功能丰富的软件包来实现这一空白,该软件包实现了最新HTTP标准和建议的客户端。
- HttpClient专为扩展而设计,同时为基本HTTP协议提供强大支持
- 详细介绍请点击官网查看 http://hc.apache.org/httpcomponents-client-5.0.x/index.html
实例
pom文件引入httoclient扩展包
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
</dependencies>
几个主要类的解释:
- HttpClint类:代表了一个http的客户端,HttpClient接口定义了大多数基本的http请求执行行为
- HttpEntity类:entity是发送或者接收消息的载体。entities可以通过request和response 获取到。
- HttpConnection类:HttpConnection代表了一个http连接
1. 以下代码片段说明了使用HttpClient经典API执行HTTP GET访问www.baidu.com并返回内容
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.charset.Charset;
public class HttpClientTest {
@Test
public void test1() throws IOException {
//存放结果
String result;
//创建httpget
HttpGet httpGet = new HttpGet("http://www.baidu.com");
System.out.println("httpget request" + httpGet.getURI());//输出获取地址
//创建默认httpClint实例
HttpClient httpClient = new DefaultHttpClient();
//执行行get请求
HttpResponse httpResponse = httpClient.execute(httpGet);
//获取响应实体
HttpEntity httpEntity = httpResponse.getEntity();
//打印响应内容,Charset.defaultCharset()解决中文乱码
result = EntityUtils.toString(httpEntity, Charset.defaultCharset());
System.out.println(result);
}
}
IDEA 输出结果
get请求增加header以及params
{
String url = "www.baidu.com";
//创建一个httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//地址拼接参数
URIBuilder uriBuilder = null;
try {
uriBuilder = new URIBuilder(url);
uriBuilder.addParameter("wd", "哈哈");
uriBuilder.addParameter("rsv_sug", "1");
HttpGet httpGet = new HttpGet(uriBuilder.build());
//添加header
httpGet.setHeader("token", "xx"));
httpGet.setHeader("traceSource", "xxx");
//执行请求
HttpResponse httpResponse = httpClient.execute(httpGet);
//获取响应结果
HttpEntity httpEntity = httpResponse.getEntity();
String result = EntityUtils.toString(httpEntity, "utf-8");
//断言响应结果不为空
Assert.assertNotNull(result);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2. 以下代码片段对上述代码做了地址优化,单独配置地址存放文件
下面为resource下applacation.properties文件内容
# 做单独配置,抽象出地址
#格式为 key ,value
#增加工具类ResourceBundle,读取该配置文件
test.url=http://localhost:8090
baidu.url = http://www.baidu.com
getCookies.uri=/getCookies
login=/login
利用moco jar包的知识,运行本地带有cookies的get请求的地址,json代码片段
[
{
"description": "这是一个带cookies参数的get请求",
"request": {
"uri": "/getCookies",
"method": "get"
},
"response": {
"cookies": {
"login": "true",
"id": "123456",
"status": "1",
"zidingyi": "cook"
},
"headers": {
"Content-Type": "text/html; charset=GBK"
},
"text": "返回一个cookies参数的get请求"
}
}
]
新建类,使用HttpClient 执行HTTP GET访问本机配置中的地址并返回内容
package cookiesget;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.ResourceBundle;
public class MyCookiesGet {
private String url;
private ResourceBundle bundle;
@BeforeTest
public void beforeTest() {
//寻找 资源路径下 resources下的properties 文件, Locale.CANADA中文转化
bundle = ResourceBundle.getBundle("applacation", Locale.CANADA);
url = bundle.getString("test.url");
}
@Test
public void testGetCoockies() throws IOException {
String result;
String uri = bundle.getString("getCookies.uri");
System.out.println(this.url + uri);
HttpGet httpGet = new HttpGet(this.url + uri);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
result = EntityUtils.toString(httpResponse.getEntity(), Charset.defaultCharset());
System.out.println(result);
}
}
执行结果
获取cookies信息
//获取cookies信息
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
CookieStore cookieStore = defaultHttpClient .getCookieStore();
List<Cookie> cookieList = cookieStore.getCookies();
for (Cookie cookie:cookieList){
String name = cookie.getName();
String value = cookie.getValue();
System.out.println("cookies name = "+name+";value="+value);
}
3. 以下代码片段是HttpClint对post带参数的请求
地址获取方式与本地post请求 与上述代码相同,
因为需要用到JSONObject包存放json数据,所以需要引入json包
post请求代码片段
@Test
public void testPostMethod() throws IOException {
String uri = bundle.getString("post.url");
//拼接最终的测试地址
String testUrl = this.url + uri;
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(testUrl);
//添加参数
JSONObject param = new JSONObject();
param.put("name", "jiutian");
param.put("age", "25");
//设置请求头信息header.添加参数到方法中
post.setHeader("content-type", "applacation/json");
StringEntity entity = new StringEntity(param.toString(), "UTF-8");
post.setEntity(entity);
//设置cookies信息,并输出想要结果
client.setCookieStore(this.store);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
//将返回结果字符串转化为json对象
JSONObject resultjson = new JSONObject(result);
String success = (String) resultjson.get("result");
String status = (String) resultjson.get("status");
//判断结果是否符合预期
Assert.assertEquals("success", success);
Assert.assertEquals("1", status);
}
pom中需要引入json包片段
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>