zoukankan      html  css  js  c++  java
  • 运用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; }
    学习时的痛苦是暂时的 未学到的痛苦是终生的
    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    上网助手(集成ipv6)windows版
    c# 串口编程
    test blog
    用于主题检测的临时日志(d020b283408c4bc68872f97ee237b663 3bfe001a32de4114a6b44005b770f6d7)
    OpenGL概述 陌陌
    [转载][转帖]谈谈我对攻读计算机研究生的看法。。。大牛的文章,见解精深独到
    滚动值的兼容问题
    js小练习去掉指定的字符组成一句话输出
    马虎将classname加到了id属性中,造成报错
    锋利的jquery读书笔记(一)
  • 原文地址:https://www.cnblogs.com/juanxincai/p/13454241.html
Copyright © 2011-2022 走看看