HttpClient远程调用基本使用(详解)

柔情只为你懂 2024-04-01 16:45 141阅读 0赞

通过HttpClient实现远程调用

如果在不同的服务要实现服务与服务之间的调用,有众多选择,如HttpclientOkhttpHttpURLConnectionRestTemplate这几种,当然还有那些封装好的框架,如feign等。这里主要讲解一下这个HttpClient的使用。

1,通过get方式实现

  1. public static String get(String url,String tokenName,String tokenValue,Map<String,String> map) {
  2. //构建客户端对象
  3. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  4. //设置参数
  5. if (CollectionUtils.isNotEmpty(map)) {
  6. //添加参数
  7. String paramData = addParamByGet(map);
  8. //拼接参数
  9. url = url + "?" + paramData ;
  10. }
  11. //String url = ""http://127.0.0.1:8080/user"
  12. HttpGet httpGet = new HttpGet(url);
  13. //响应体
  14. CloseableHttpResponse response;
  15. try {
  16. //添加请求头,添加token
  17. //httpGet.addHeader("token", "eyJ0eXAiOiJKc29uV2ViVG9rZW4iLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOi");
  18. httpGet.addHeader(tokenName, tokenValue);
  19. //添加请求配置,设置响应时间等
  20. RequestConfig requestConfig = RequestConfig.custom()
  21. .setSocketTimeout(2000) //服务器响应超时时间
  22. .setConnectionRequestTimeout(2000) //连接服务器超时时间
  23. .build();
  24. //将配置信息添加到 httpGet 中
  25. httpGet.setConfig(requestConfig);
  26. //调用接口,获取响应
  27. response = httpClient.execute(httpGet);
  28. //将响应转化为一个结果集
  29. HttpEntity entity = response.getEntity();
  30. //将内容转化为字符串,并且设定指定字符集
  31. String result= EntityUtils.toString(entity, "UTF-8");
  32. //最终将结果集返回
  33. return result;
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. } finally {
  37. //资源释放
  38. if (httpGet != null) {
  39. try {
  40. httpGet.clone();
  41. } catch (CloneNotSupportedException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. if (httpClient != null) {
  46. try {
  47. httpClient.close();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. }
  53. }

get请求添加参数

  1. /**
  2. * get添加参数
  3. */
  4. public static StringBuilder addParamByGet(Map<String,String> map){
  5. StringBuilder param = new StringBuilder();
  6. //遍历参数
  7. for (Map.Entry<String, String> m :map.entrySet()) {
  8. param.append(m.getKey()).append("=").append(m.getValue()).append("&");
  9. }
  10. return param;
  11. }

2,通过post的方式实现

里面有一些token,参数之类的,如果不用,直接将代码注释即可

  1. public static String post(String url, String tokenName,String tokenValue, Map<String,String> map) throws IOException {
  2. //构建客户端对象
  3. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  4. CloseableHttpResponse response = null;
  5. try {
  6. //创建http post请求对象 这个url可以手动封装一个
  7. HttpPost post = new HttpPost("http://127.0.0.1:8080/user/addUser");
  8. //设置请求头
  9. //post.setHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwidXN" +
  10. // "lckluZm8iOnsidXNlcklkIjoxNTg5ODIxMzMwNTY1NjQ0Mjg5fSwiZXhwIjoxNjY4MDU5MzQ3LCJpYXQiOjE2N" +
  11. // "jc5NzI5NDd9.mcmgzc0yEyTyfeo-2D5vpaYhdyD9LFBwCwP8s30r0Hs");
  12. post.addHeader(tokenName, tokenValue);
  13. //设置文本类型
  14. post.setHeader("Content-Type", "application/json");
  15. //如果只有一两个参数的话,也可以通过这个反转义字符手动传参变成json格式,反正最终是要转成json的形式的
  16. //post.setEntity(new StringEntity("{\"type\":\"1\"}", "UTF-8"));
  17. //构建参数
  18. if (CollectionUtils.isNotEmpty(map)){
  19. JSONObject jo = new JSONObject();
  20. //增加参数
  21. addParam(map,jo);
  22. post.setEntity(new StringEntity(jo.toString(), ContentType.APPLICATION_JSON));
  23. }else {
  24. post.setEntity(new StringEntity(null, ContentType.APPLICATION_JSON));
  25. }
  26. //创建响应对象
  27. response = httpClient.execute(post);
  28. /**
  29. * 由于响应接口返回的是一个字符串,因此需要转换
  30. * 响应体数据封装在HttpEntity对象中
  31. */
  32. String result = EntityUtils.toString(response.getEntity(), "utf-8");
  33. return result;
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. } finally {
  37. //关闭资源
  38. response.close();
  39. httpClient.close();
  40. }
  41. }

post请求添加参数

  1. /**
  2. * post添加参数
  3. */
  4. public static JSONObject addParam(Map < String, String > map, JSONObject jsonObject) {
  5. for (Map.Entry < String, String > entry: map.entrySet()) {
  6. jsonObject.put(entry.getKey(), entry.getValue());
  7. }
  8. return jsonObject;
  9. }

3,解析返回数据

上面两种方式都是返回一个json格式的字符串,因此可以将这个字符串解析,或者直接在方法里面解析,我这里选择在外面解析

  1. public static vois mian(String Args[]) {
  2. //调用get请求,可以将里面的url,token等作为参数传入
  3. String url = "localhost:8080/user/message";
  4. String tokenName = "token";
  5. String tokenValue = "xxx";
  6. String message = get(url,tokenName,tokenValue,null);
  7. //如果里面有多条数据,那么可以用数组方式解析,即使一条数据,也是可以通过这个解析的
  8. JSONArray jsonArray = JSONArray.parseArray(message);
  9. //遍历
  10. List<User> list = new ArrayList<>();
  11. jsonArray.stream().forEach(json - > {
  12. JSONObject jsonObject = JSONArray.parseObject(json.toString());
  13. User user = JSON.toJavaObject(jsonObject, User.class);
  14. list.add(user);
  15. });
  16. //遍历全部的用户
  17. list.stream.forEach(e->{
  18. System.out.println(e)});
  19. }

发表评论

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

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

相关阅读

    相关 HttpClient使用详解

    1. 什么是HttpClient HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访