Java专题 httpClient对接Restful接口 添加请求头信息 +POST,GET 完整案例

公共部分代码

公共参数

public static final int CONNECTION_TIMEOUT = 60000;// 连接超时时间

public static final int CONNECTION_REQUEST_TIMEOUT = 60000;// 请求超时时间

public static final int SOCKET_TIMEOUT = 60000;// 数据读取等待超时

public static final String DEFAULT_ENCODING = "UTF-8";// 默认编码

资源关闭公共方法(若不需要可以不加)

 /**
     * 释放资源
     *
     * @param httpClient
     * @param response
     */
    private static void closeResource(CloseableHttpClient httpClient, CloseableHttpResponse response) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                log.error("释放response资源异常:" + e.getMessage());
            }
        }

        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error("释放httpclient资源异常:" + e.getMessage());
            }
        }
    }

转码 (若不需要可以不加)

private static String encodeHeader(String value) throws UnsupportedEncodingException {
    if (StringUtils.isEmpty(value)) {
        return value;
    }
    return URLEncoder.encode(value, DEFAULT_ENCODING);
}

POST (传入Json格式参数)

这里传入参数为url以及JsonStr
url 为实际的请求全路径 例如http://192.168.31.106:44939/dataMethod/api/resultful/list
jsonStr为 将一个对象或者Map形式的对象 直接通过 json 或者 gson 转成了json字符串的形式


public static String handlePost(String url, String jsonParam){
    // 创建Httpclient对象 
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 设置请求超时时间
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT)   //设置连接超时时间
            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) // 设置请求超时时间
            .setSocketTimeout(SOCKET_TIMEOUT).setRedirectsEnabled(true)//默认允许自动重定向
            .build();

    CloseableHttpResponse response = null;
    String resultString = "";

    try {
        // 如果需要从配置文件获取信息的话 这样写  否则可以直接删掉
        Properties properties = PropertiesLoaderUtils.loadAllProperties("a.properties");
        String key1= properties.getProperty("key1");
        String key2= properties.getProperty("key2");
        String key3= properties.getProperty("key3");
        String key4= properties.getProperty("key4");

		// 构建httpPost请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        // 请求头添加 setheader 如果有一样的key 则覆盖,否则新增  若使用addheader 不管有无均添加
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
        httpPost.setHeader("HeaderData1", encodeHeader(key1));
        httpPost.setHeader("HeaderData2", encodeHeader(key2));
        httpPost.setHeader("HeaderData3", encodeHeader(key3));
        // 这一行是授权的头信息的键值 没有同样可以不加
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, encodeHeader(key4));

        httpPost.setEntity(new StringEntity(jsonParam));
        // 创建请求内容 ,发送json数据需要设置contentType
        StringEntity entity = new StringEntity(jsonParam, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);
        // 执行http请求 
        response = httpClient.execute(httpPost);
        
        // 判断是否是返回状态是200 (正常)
        if(response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK){
        // resultString 即为返回的数据 也是字符串形式
            resultString = EntityUtils.toString(response.getEntity());
        }else{
            logger.info("post类型接口"+url+"未能获取到正常的返回值 当前状态码"+response.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        logger.error("Post发生异常异常:" + e.getMessage());
    }finally {
        closeResource(httpClient, response);
    }

    return resultString;
}
POST传入一般对象(模拟表单) 若参数为Map形式则做如下修改
Map<String, String> param   //入参为Map

// 参数传入部分可以用以下形式 其他部分不用修改
 // 创建参数列表 
  if (param != null) { 
        List<NameValuePair> paramList = new ArrayList<>(); 
        for (String key : param.keySet()) { 			// key为 map中的key
            paramList.add(new BasicNameValuePair(key, param.get(key))); 
        } 
        // 模拟表单 
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); 
        httpPost.setEntity(entity); 
    } 
    // 参数最终添加到了entity中

//然后就是正常的执行请求
response = httpClient.execute(httpPost);
......

GET

public static String handleGet(String url, String jsonParam){
    // 创建Httpclient对象 
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 设置请求超时时间
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT)   //设置连接超时时间
            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) // 设置请求超时时间
            .setSocketTimeout(SOCKET_TIMEOUT).setRedirectsEnabled(true)//默认允许自动重定向
            .build();

    CloseableHttpResponse response = null;
    String resultString = "";

    try {
        // 地址获取
        Properties properties = PropertiesLoaderUtils.loadAllProperties("a.properties");
        String key1= properties.getProperty("key1");
        String key2= properties.getProperty("key2");
        String key3= properties.getProperty("key3");
        String key4= properties.getProperty("key4");

        // 创建uri 
        URIBuilder builder = new URIBuilder(url);
        // 将要拼接的参数加入到Map中
        Map<String, String> map = (Map<String, String>) JSON.parse(jsonParam);
        // 参数拼接到原有请求地址中
        if (map != null) {
            for (Map.Entry<String, String> key : map.entrySet()) {
                builder.addParameter(key.getKey(), key.getValue());
            }
        }
        URI uri = builder.build();
        String uriStr = uri.toString();

        // 创建http GET请求 
        HttpGet httpGet = new HttpGet(uriStr);

        // 请求头添加  setheader 如果有一样的key 则覆盖,否则新增  若使用addheader 不管有无均添加
        httpGet.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
        httpGet.setHeader("key1", encodeHeader(key1));
        httpGet.setHeader("key2", encodeHeader(key2));
        httpGet.setHeader("key3", encodeHeader(key3));
        // 这一行是授权的头信息的键值 没有同样可以不加
        httpGet.setHeader(HttpHeaders.AUTHORIZATION, encodeHeader(key4));

        httpGet.setConfig(requestConfig);

        // 执行http请求 
        response = httpClient.execute(httpGet);
        // 判断是否是返回状态是200 (正常)
        if(response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK){
        // 返回的结果为字符串类型
            resultString = EntityUtils.toString(response.getEntity());
        }else{
            logger.info("请求接口"+url+"未能获取到正常的返回值 当前状态码"+response.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        logger.error("Get发生异常异常:" + e.getMessage());
    }finally {
        closeResource(httpClient, response);
    }

    return resultString;
}

可抽取的公共部分

配置文件内容获取可以抽取
获取返回值可以获取
添加config的内容可以抽取
设置请求头也可以抽取

接收端以及发送端对应controller中的写法

JSON格式

// 发送端  请求端
// post  json
    Map<String,String> map=new HashMap<String,String> ();
    map.put("name", "1");
    map.put("name2", "2");
    String param=JSONObject.fromObject(map).toString();
    String str = HttpClientUtil.handelPostJson(url,param);
}

接受处

// json格式  接受处  服务端
public String jsonGet(HttpServletRequest request){
    StringBuffer str = new StringBuffer();  
    try { 
         BufferedInputStream in = new BufferedInputStream(request.getInputStream()); 
         int i; 
         char chr; 
         while ((i=in.read())!=-1) { 
              chr=(char)i; 
              str.append(chr); 
          } 
      }catch (Exception e) { 
           log.error(e);
      } 
      String string = str.toString();
      return string;
}

一般格式

发送请求处

Map<String,String> map=new HashMap<String,String> ();
    map.put("name", "1");
    map.put("name2", "2");
    String str = HttpClientUtil.dohandelGet(url, map);

接受获取处

public String restMethod(HttpServletRequest request){
 String username = request.getParameter("name");
 return username;
}

什么是restful接口?
点此跳转

https请求报错PKIX?
点这里

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值