详解HttpClient用法

  //post路径传参

  @RequestMapping("/findAllPost/{page}/{size}")

  public String findAll(@PathVariable("page") int page,@PathVariable("size") int size) throws Exception {

  //获得Http客户端

  CloseableHttpClient build = HttpClientBuilder.create().build();

  //创建post请求

  HttpPost httpPost = new HttpPost("http://localhost:8088/position/findAll/"+page+"/"+size);

  //执行请求

  CloseableHttpResponse execute = build.execute(httpPost);

  //解析返回值

  StatusLine statusLine = execute.getStatusLine();

  //获取到返回状态码

  System.out.println("状态码为:"+statusLine.getStatusCode());

  String s = EntityUtils.toString(execute.getEntity());

  build.close();

  execute.close();

  return s;

  }

  //post map传参

  @RequestMapping("findById")

  public String findById(@RequestParam("id") Integer id)throws Exception{

  //创建httpclicent请求对象

  CloseableHttpClient build = HttpClientBuilder.create().build();

  //声明请求方式

  HttpPost httpPost = new HttpPost("http://localhost:8088/position/findById");

  //声明携带参数

  Map map=new HashMap<>();

  map.put("id",id);

  //将map转换为json格式

  Object o = JSONObject.toJSON(map);

  //设置请求 参数的编码格式

  StringEntity stringEntity = new StringEntity(o.toString(), "utf-8");

  //将参数设置到请求对象中

  httpPost.setEntity(stringEntity);

  //设置content-Type

  httpPost.setHeader("Content-Type","application/json");

  //执行请求

  CloseableHttpResponse execute = build.execute(httpPost);

  //解析返回值

  StatusLine statusLine = execute.getStatusLine();

  //获取到返回状态码

  System.out.println("状态码为:"+statusLine.getStatusCode());

  String s = EntityUtils.toString(execute.getEntity());

  build.close();

  execute.close();

  return s;

  }

相关文章