第一步:jar包
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
第一种:HttpClient发送GET请求
public void HttpClientGet() throws Exception {
// 获取http客户端
CloseableHttpClient client = HttpClients.createDefault();
// 通过HttpGet方式来实现我们的get请求
HttpGet httpGet = new HttpGet("http://192.168.100.10:8080/project/login?username=zhangsan&password=123");
// 通过client调用execute方法,得到我们的执行结果就是一个response,所有的数据都封装在response里面了
CloseableHttpResponse httpResponse = client.execute(httpGet);
// HttpEntity
// 是一个中间的桥梁,在httpClient里面,是连接我们的请求与响应的一个中间桥梁,所有的请求参数都是通过HttpEntity携带过去的
// 所有的响应的数据,也全部都是封装在HttpEntity里面
HttpEntity entity = httpResponse.getEntity();
// 通过EntityUtils 来将我们的数据转换成字符串
String str = EntityUtils.toString(entity, "UTF-8");
// EntityUtils.toString(entity)
System.out.println(str);
// 关闭
Response.close();
}
第一种:HttpClient发送POST请求
public void HttpClientPost() throws Exception {
// 获取默认的请求客户端
CloseableHttpClient client = HttpClients.createDefault();
// 通过HttpPost来发送post请求
HttpPost httpPost = new HttpPost("http://www.itcast.cn");
/*
* post带参数开始
*/
// 第三步:构造list集合,往里面丢数据
List<NameValuePair> list = new ArrayList<NameValuePair>();
BasicNameValuePair basicNameValuePair1 = new BasicNameValuePair("username", "zhangsan");
BasicNameValuePair basicNameValuePair2 = new BasicNameValuePair("password", "123");
list.add(basicNameValuePair1);
list.add(basicNameValuePair2);
// 第二步:我们发现Entity是一个接口,所以只能找实现类,发现实现类又需要一个集合,集合的泛型是NameValuePair类型
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
// 第一步:通过setEntity 将我们的entity对象传递过去
httpPost.setEntity(formEntity);
/*
* post带参数结束
*/
// HttpEntity
// 是一个中间的桥梁,在httpClient里面,是连接我们的请求与响应的一个中间桥梁,所有的请求参数都是通过HttpEntity携带过去的
// 通过client来执行请求,获取一个响应结果
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String str = EntityUtils.toString(entity, "UTF-8");
System.out.println(str);
// 关闭
response.close();
}