运用HttpClient调用其它项目的接口

首先引入依赖

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.6</version>
    </dependency>
复制代码
private final int timeOut = 500;
public
String queryString(String code) { // 获得Http客户端(可以理解为:先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 参数 StringBuffer params = new StringBuffer(); try { // 字符数据最好encoding下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去) params.append("code=" + URLEncoder.encode(code, "utf-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 创建Get请求 HttpGet httpGet = new HttpGet(192.168.xx.xx:port/xx/queryString); // 响应模型 CloseableHttpResponse response = null; try { // 配置信息 RequestConfig requestConfig = RequestConfig.custom() // 设置连接超时时间(单位毫秒) .setConnectTimeout(timeOut) // 设置请求超时时间(单位毫秒) .setConnectionRequestTimeout(timeOut) // socket读写超时时间(单位毫秒) .setSocketTimeout(timeOut) // 设置是否允许重定向(默认为true) .setRedirectsEnabled(true).build(); // 将上面的配置信息 运用到这个Get请求里 httpGet.setConfig(requestConfig); // 由客户端执行(发送)Get请求 response = httpClient.execute(httpGet); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); String json = EntityUtils.toString(responseEntity); String result = JsonUtil.fromJson(json, String.class); if(null!= result ){ return result ; } } else { return null; } } catch (Exception e) { //todo 此处做异常处理返回 //e.printStackTrace();return ("与数据服务连接异常!"); } finally { closeClient(httpClient, response); } return null; }
复制代码

 

posted @   卷心菜的奇妙历险  阅读(491)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示