java 通过HTTPClient工具类发送请求

妖狐艹你老母 2022-05-09 03:38 333阅读 0赞

客户端code 如下:

  1. package com.eas.bojoy;
  2. import java.io.IOException;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.ParseException;
  5. import org.apache.http.client.ClientProtocolException;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.methods.CloseableHttpResponse;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.impl.client.CloseableHttpClient;
  10. import org.apache.http.impl.client.HttpClients;
  11. import org.apache.http.util.EntityUtils;
  12. public class TestHttpClient {
  13. public static void main(String[] args) {
  14. // 1.获得一个HttpClient对象
  15. CloseableHttpClient httpClient = HttpClients.createDefault();
  16. // 2.生成一个HttpGet请求
  17. HttpGet httpGet = new HttpGet("http://localhost:8080/testSSM/depts");
  18. CloseableHttpResponse response = null;
  19. // 3.执行get请求
  20. try {
  21. response = httpClient.execute(httpGet);
  22. } catch (IOException e1) {
  23. e1.printStackTrace();
  24. }
  25. String result="";
  26. HttpEntity entity = response.getEntity();
  27. try {
  28. if(entity != null)
  29. result = EntityUtils.toString(entity);
  30. } catch (ParseException | IOException e) {
  31. e.printStackTrace();
  32. }finally {
  33. try {
  34. if(response != null)
  35. response.close();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. System.out.println("结果为:"+result);
  41. }
  42. }

服务端code如下:

  1. @RequestMapping(value="/depts")
  2. @ResponseBody
  3. public Msg getDepts(){
  4. List<Department> list = departmentService.getDepts();
  5. return Msg.success().add("depts", list);
  6. }

result结果如下:

70

发表评论

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

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

相关阅读