HttpClient发送http请求

技术 置顶 精帖
0 904
peng49
peng49 2020-09-02 01:45:41
 

1. pom.xml 引入坐标

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.3</version>
  5. </dependency>

2.测试

发送GET请求
  1. //1.创建客户端
  2. CloseableHttpClient httpClient = HttpClients.createDefault();
  3. //2.声明get请求
  4. HttpGet request = new HttpGet("http://www.baidu.com");
  5. //3.发送请求
  6. CloseableHttpResponse response = httpClient.execute(request);
  7. //4.判断状态码
  8. if (response.getStatusLine().getStatusCode() == 200) {
  9. HttpEntity entity = response.getEntity();
  10. //使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
  11. String string = EntityUtils.toString(entity, "UTF-8");
  12. System.out.println(string);
  13. }
  14. //5.关闭资源
  15. response.close();
  16. httpClient.close();
发送POST请求
  1. //获取客户端
  2. CloseableHttpClient client = HttpClients.createDefault();
  3. //声明POST请求
  4. HttpPost request = new HttpPost("https://gitee.com/oauth/token");
  5. //设置User-Agent
  6. request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
  7. //构建请求参数
  8. ArrayList<NameValuePair> parameters = new ArrayList<>();
  9. parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
  10. parameters.add(new BasicNameValuePair("code", "xxx"));
  11. parameters.add(new BasicNameValuePair("client_id", "xxx"));
  12. parameters.add(new BasicNameValuePair("client_secret", "xxx"));
  13. parameters.add(new BasicNameValuePair("redirect_uri", "http://localhost:8001/oauth/gitee/callback"));
  14. UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
  15. //设置请求的参数
  16. request.setEntity(urlEncodedFormEntity);
  17. //发送请求
  18. CloseableHttpResponse response = client.execute(request);
  19. System.out.println(response.getStatusLine().getStatusCode());
  20. if (response.getStatusLine().getStatusCode() == 200) {
  21. HttpEntity entity = response.getEntity();
  22. String body = EntityUtils.toString(entity, "UTF-8");
  23. System.out.println(body);
  24. } else {
  25. System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
  26. }
  27. //关闭资源
  28. response.close();
  29. client.close();
回帖
登录
忘记密码?