HttpClient 请求传参时如何优雅的进行编码,拒绝url人工拼接

我们在利用HttpClient进行远程调用时,第三方提供的接口如下:

这种接口我们用get、post请求都能调用,但是会有一个问题,传参,@RequestParam 注解表示,传参非body体,我们只能接在

/updateUserPhoto这个url后面,就是/updateUserPhoto?userId=""&photoUrl="",很多人在编码时,也总是大学生刚毕业似的,硬性拼接,那么,到底如何优雅的进行参数传递呢?好了,不啰嗦,直接贴代码吧

    /**
    * get 方式传参
    * @param url
    * @param params
    * @param heads
    * @return
    */
   public static String get(String url, Map<String, String> params, Map<String, String> heads) {
      // 获取连接客户端工具
      CloseableHttpClient httpClient = HttpClients.createDefault();
      CloseableHttpResponse response = null;
      try {
         /*
          * 由于GET请求的参数都是拼装在URL地址后方,所以我们要构建一个URL,带参数
          */
         URIBuilder uriBuilder = new URIBuilder(url);
         if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
               uriBuilder.addParameter(entry.getKey(), entry.getValue());
            }
         }
//       uriBuilder.setParameters(list);
         // 根据带参数的URI对象构建GET请求对象
         HttpGet httpGet = new HttpGet(uriBuilder.build());
         // 执行请求
         response = httpClient.execute(httpGet);
         // 使用Apache提供的工具类进行转换成字符串
         return EntityUtils.toString(response.getEntity());
      } catch (ClientProtocolException e) {
         System.err.println("Http协议出现问题");
      } catch (ParseException e) {
         System.err.println("解析错误");
      } catch (URISyntaxException e) {
         System.err.println("URI解析异常");
      } catch (IOException e) {
         System.err.println("IO异常");
      } finally {
         // 释放连接
         if (null != response) {
            try {
               response.close();
               httpClient.close();
            } catch (IOException e) {
            }
         }
      }
      return null;
   }

这种方式核心就是URIBuilder类,我们调用HttpUtil.get()方法时,只用把参数封装在map里面就行,拒绝了url字符串拼接,避免粗心大意导致的错误,而且十分优雅,高大上!

猜你喜欢

转载自blog.csdn.net/hnifgvbjrb/article/details/84100555