Verwenden Sie HttpClient, um die Schnittstelle in Java aufzurufen

Verwenden Sie HttpClient, um die Schnittstelle in Java aufzurufen

1. Die Hauptfunktionen von HttpClient

(1) Alle HTTP-Methoden (GET, POST, PUT, DELETE usw.) sind implementiert

(2) Automatische Lenkung unterstützen

(3) Unterstützung des HTTPS-Protokolls

(4) Proxyserver usw. unterstützen.

Kommen wir zur Sache! ! ! ! Code hochladen

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

Kein Gegner

Es gibt tatsächlich so viele Codes und es gibt viele Formen. Sie können sich darauf beziehen und darüber schreiben. Ich werde es aufschreiben und hoffe, dass jeder es auch lernen wird. Ich mache auch eine Aufzeichnung, sonst kann sich mein Gehirn nicht daran erinnern, hahaha!

Ich denke du magst

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