• 运用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; }
    学习时的痛苦是暂时的 未学到的痛苦是终生的
    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    vue组件的通信
    vue基础
    vue项目总结
    路由(4)传参
    路由(3)
    第一次作业
    JAVA-2.0-homework
    JAVA-2.0-上机
    JAVA-1.9-homework
    JAVA-1.9-上机
  • 原文地址:https://www.cnblogs.com/juanxincai/p/13454241.html
Copyright © 2020-2023  润新知