Use HttpClient to call the interface in java

Use HttpClient to call the interface in java

1. The main functions provided by HttpClient

(1) All HTTP methods (GET, POST, PUT, DELETE, etc.) are implemented

(2) Support automatic steering

(3) Support HTTPS protocol

(4) Support proxy server, etc.

Let's get down to business! ! ! ! Upload code

Code

 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;
    }

No opponent

There are actually so many codes, and there are many forms. You can refer to it and write about it. I will write it out and hope that everyone will learn it too. I am also making a record, otherwise my brain can't remember it hahaha!

Guess you like

Origin blog.csdn.net/m0_46379371/article/details/108983897