Apache HttpClient用法代码实例

向右看齐 2022-05-30 09:51 306阅读 0赞

首先,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、关闭连接、释放资源

  1. import org.apache.http.HttpEntity;
  2. import org.apache.http.HttpStatus;
  3. import org.apache.http.client.methods.CloseableHttpResponse;
  4. import org.apache.http.client.methods.HttpGet;
  5. import org.apache.http.impl.client.CloseableHttpClient;
  6. import org.apache.http.impl.client.HttpClients;
  7. import org.apache.http.util.EntityUtils;
  8. import java.io.BufferedReader;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.InputStreamReader;
  12. public static void main(String[] args){
  13. String url="http://www.baidu.com";
  14. //1、创建httpClient
  15. CloseableHttpClient client = HttpClients.createDefault();
  16. //2、使用get方法
  17. HttpGet httpGet = new HttpGet(url);
  18. InputStream is = null;
  19. CloseableHttpResponse response = null;
  20. try{
  21. //3、执行请求、获取响应
  22. response = client.execute(httpGet);
  23. //4、获取到数据
  24. if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
  25. //(1)、第一种方法:使用EntityUtils工具类
  26. HttpEntity entity = response.getEntity();
  27. System.out.println(EntityUtils.toString(entity,"utf-8"));
  28. //关闭流
  29. EntityUtils.consume(entity);
  30. //(2)、第二种方法:使用流(使用流的时候注意最后要关闭流)
  31. is = entity.getContent();
  32. BufferedReader br = new BufferedReader(new InputStreamReader(is));
  33. String line="";
  34. while((line=br.readLine())!=null){
  35. System.out.println(line);
  36. }
  37. }
  38. }catch (IOException e){
  39. e.printStackTrace();
  40. }finally {
  41. if(is!=null){
  42. try {
  43. is.close();
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }
  47. }
  48. if(response!=null){
  49. try {
  50. response.close();
  51. } catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. }
  56. }

发表评论

表情:
评论列表 (有 0 条评论,306人围观)

还没有评论,来说两句吧...

相关阅读