java中使用HttpClient调用接口

java中使用HttpClient调用接口

1.HttpClient 提供的主要的功能

(1)实现了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器等

直接言归正传了!!!!上代码

代码

 public static String sendPutForm(String url,  Map<String,String> map, String encoding) throws ParseException, IOException {
    
    
        String body = "";
        // 打印了一下我推送的json数据
        log.info("我推送的json数据:" + map);
        log.info("我推送的url:" + url);
        CloseableHttpResponse response = null;
        ///获得Http客户端
        CloseableHttpClient client = HttpClients.createDefault();
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
    
    
            System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
            parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
		// 配置信息
		// 设置连接超时时间(单位毫秒)
		// 设置请求超时时间(单位毫秒)
		// socket读写超时时间(单位毫秒)
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000).setConnectionRequestTimeout(50000)
                .setSocketTimeout(50000).build();
        // 向指定资源位置上传内容// 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        httpPost.setEntity(formEntity);
        try {
    
    
            response = client.execute(httpPost);

            // 通过response中的getEntity()方法获取返回值
            HttpEntity entity = response.getEntity();
            if (entity != null) {
    
    
                body = EntityUtils.toString(entity, encoding);
            }
        } catch (Exception e) {
    
    
            // TODO: handle exception
            e.printStackTrace();
        } finally {
    
    
            httpPost.abort();
            if (response != null) {
    
    
                EntityUtils.consumeQuietly(response.getEntity());
            }
        }

        log.info("body:" + body);
        return body;
    }

没对手

代码其实就是这么多,还有好多形式。大家可以参考写一下,我这呢写出来希望大家也学习,我这也是做个记录不然脑子不行记不住哈哈哈!

猜你喜欢

转载自blog.csdn.net/m0_46379371/article/details/108983897
今日推荐