Apache HttpClient用法代码实例
首先,HttpClient可以做什么用?
1、用于网上抓包
2、模拟用户登陆
相关pom依赖包:
httpclient、httpclient-cache、httpmime
总共分为6个步骤:
1、创建HttpClient对象
2、创建需要方法的实例
方法 | 描述 | 是否包含主体 |
GET | 从服务器获取一份文档 | 否 |
HEAD | 只从服务器获取文档的首部 | 否 |
POST | 向服务器发送需要处理的数据 | 是 |
PUT | 将请求的主体部分存储在服务器上 | 是 |
TRACE | 对可能经过代理服务器传送到服务器上去的报文进行追踪 | 否 |
OPTIONS | 决定可以在服务器上执行哪些方法 | 否 |
DELETE | 从服务器上删除一份文档 | 否 |
3.如果有请求参数的话,Get方法直接写在url后面,例如
HttpGet httpget = new HttpGet( “http://www.google.com/search?hl=zhCN&q=httpclient&btnG=Google+Search&aq=f&oq=”);
或者使用setParameter来设置参数
URI uri = new URIBuilder()
.setScheme(“http”)
.setHost(“www.google.com”)
.setPath(“/ search”)
.setParameter(“q”,“httpclient”)
.build();
HttpGet httpget = new HttpGet(uri);
4、发送请求
5、获取请求结果
6、关闭连接、释放资源
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public static void main(String[] args){
String url="http://www.baidu.com";
//1、创建httpClient
CloseableHttpClient client = HttpClients.createDefault();
//2、使用get方法
HttpGet httpGet = new HttpGet(url);
InputStream is = null;
CloseableHttpResponse response = null;
try{
//3、执行请求、获取响应
response = client.execute(httpGet);
//4、获取到数据
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//(1)、第一种方法:使用EntityUtils工具类
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity,"utf-8"));
//关闭流
EntityUtils.consume(entity);
//(2)、第二种方法:使用流(使用流的时候注意最后要关闭流)
is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line="";
while((line=br.readLine())!=null){
System.out.println(line);
}
}
}catch (IOException e){
e.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(response!=null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
还没有评论,来说两句吧...