所需jar包

  1. commons-logging
  2. httpclient
  3. httpcore

使用

  1. //获得Http客户端
  2. CloseableHttpClient httpClient = HttpClients.createDefault();
  3. // 创建Get请求
  4. HttpGet httpGet = new HttpGet("url");
  5. //创建Post请求
  6. HttpPost httpPost = new HttpPost("url");
  7. //获取返回方式
  8. CloseableHttpResponse res = httpClient.execute(请求方式)
  9. //获取返回的集合
  10. HttpEntity entity = res.getEntity()
  11. //EntityUtils工具类将返回值进行字符集转换字符串 s就是返回值
  12. String s = EntityUtils.toString(entity, "UTF-8");
  13. //通过字节流的方式获取响应
  14. byte[] bytes = EntityUtils.toByteArray(entity);
  15. //确保流关闭
  16. EntityUtils.consume(entity);
  17. ------------------
  18. //解决被认为不是真人的情况设置请求头User-Agent 值 伪装成浏览器 否则可能会出现无法请求网址的情况
  19. httpGet.addHeader("User-Agent:","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36");
  20. //解决爬虫不能获取图片的情况 网址是图片的网址
  21. httpGet.addHeader("Referer","网址“)

url地址上 传参有特殊字符需要进行Urlencode编码

  1. String pass = "123+123"//有+特殊字符
  2. String urlPass = URLEncode.encode(pass,"UTF-8")//在当做参数才可以

设置访问代理

  1. HttpGet httpGet = new HttpGet("http://www.baidu.com");
  2. HttpHost httpHost = new HttpHost("ip",port(int));
  3. RequestConfig build = RequestConfig.custom().setProxy(httpHost).build();
  4. httpGet.setConfig(build);

Post请求—表单提交url方式

  1. CloseableHttpClient httpClient = HttpClients.createDefault();
  2. HttpPost httpPost = new HttpPost("http://www.baidu.com");
  3. //设置请求方式-表单提交applition/x-www-form-urlencoded
  4. httpPost.addHeader("Content-type","application/x-www-form-urlencoded;charset=utf-8");
  5. //设置参数 表单提交的方式---UrlEncodedFormEntity
  6. List<NameValuePair> list = new ArrayList<>();
  7. list.add(new BasicNameValuePair("username","张三"));
  8. UrlEncodedFormEntity httpEntity = new UrlEncodedFormEntity(list,"UTF-8");
  9. httpPost.setEntity(httpEntity);
  10. //---------------------------------------
  11. CloseableHttpResponse execute = httpClient.execute(httpPost);
  12. HttpEntity entity = execute.getEntity();
  13. String s = EntityUtils.toString(entity, "UTF-8");
  14. //确保流关闭
  15. EntityUtils.consume(entity);
  16. //------------------------------------------------------------------
  17. //发送application/jsoPost请求

Post请求—json提交

  1. CloseableHttpClient httpClient = HttpClients.createDefault();
  2. HttpPost httpPost = new HttpPost("http://www.baidu.com");
  3. //设置提交方式--json方式
  4. httpPost.addHeader("Content-type","application/json;charset=utf-8");
  5. //设置参数
  6. StringEntity stringEntity = new StringEntity("json字符串","UTF-8");
  7. httpPost.setEntity(stringEntity);
  8. CloseableHttpResponse execute = httpClient.execute(httpPost);
  9. HttpEntity entity = execute.getEntity();
  10. String s = EntityUtils.toString(entity, "UTF-8");
  11. //确保流关闭
  12. EntityUtils.consume(entity);