org.apache.httpcomponents.httpclient

apache org doc :http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e49

依赖:

<!--  https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.3</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
</dependency>

  

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.log4j.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpDemo {
    private static Logger LOGGER = Logger.getLogger(HttpDemo.class);
    static CloseableHttpResponse response;
    static HttpEntity entity;

    /**
     * this is ssl ignore https CloseableClient
     */
    public static CloseableHttpClient sslIgnoreClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        CloseableHttpClient client = null;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();
        client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

        return client;
    }

    /**
     * http get method
     */
    static String doGet(String url, Map<Object, Object> header) throws KeyStoreException, IOException,
            KeyManagementException, NoSuchAlgorithmException {
        String result = null;  // initialize result
        CloseableHttpClient request = sslIgnoreClient();
        HttpGet msg = new HttpGet(url);
        if (header != null) {
            header.forEach((key,value)-> {msg.addHeader(key.toString(),value.toString()); });

        }
        response = request.execute(msg);
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            entity = response.getEntity();
            result = EntityUtils.toString(entity,"UTF-8");
        }
        return result;
    }
    /**  String body is json type*/
    static String doPost(String url,String body, Map<Object,Object> header)throws KeyStoreException, IOException,
    KeyManagementException, NoSuchAlgorithmException{
        String result =null;
        CloseableHttpClient request = sslIgnoreClient();
        HttpPost msg = new HttpPost(url);
        if (header !=null){
            header.forEach((key,value)-> {msg.addHeader(key.toString(),value.toString()); });
        }
        msg.setEntity(new StringEntity(body));
        response = request.execute(msg);
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            entity = response.getEntity();
            result = EntityUtils.toString(entity,"UTF-8");
        }
        return result;
    }

    /**  do post form-data  */
    static String doPostParam(String url, Map<Object,Object> header,Map<Object,Object> params)throws KeyStoreException, IOException,
            KeyManagementException, NoSuchAlgorithmException{
        String result = null;
        CloseableHttpClient request =sslIgnoreClient();
        HttpPost msg = new HttpPost();
        if (header !=null){
            header.forEach((key,value)-> {msg.addHeader(key.toString(),value.toString()); });
        }
        List<BasicNameValuePair> paramList=new ArrayList<>();
        params.forEach((key,value)->{paramList.add(new BasicNameValuePair(key.toString(),value.toString()));});
        HttpEntity formEntity = new UrlEncodedFormEntity(paramList,"utf-8");
        msg.setEntity(formEntity);
        response = request.execute(msg);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            entity = response.getEntity();
            result = EntityUtils.toString(entity,"UTF-8");
        }
        return result;
    }

    /**  do  upload and download operation*/
    static  void uploadFile(){

    }

}

  

原文地址:https://www.cnblogs.com/SunshineKimi/p/12222791.html

时间: 2024-10-18 11:55:01

org.apache.httpcomponents.httpclient的相关文章

org.apache.httpcomponents httpclient 发起HTTP JSON请求

1. pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> 2. HttpClient.java package com.midea.clean.util; import java.io

org.apache.httpcomponents:httpclient 工具类

基于httpclient 版本4.4.1 因为http连接需要三次握手,在需要频繁调用时浪费资源和时间 故采用连接池的方式连接 根据实际需要更改  连接池最大连接数.路由最大连接数 另一个需要注意的是 // 释放Socket流 response.close(); // 释放Connection // httpClient.close(); 1 import org.apache.http.HttpEntity; 2 import org.apache.http.NameValuePair; 3

阿帕奇 Http 组件(Apache HttpComponents)- Apache 翻译过来好像都不认识了吧

Apache HttpComponents 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. 标题也就没啥可翻的了,就是 Apache 提供的免费开源的 Http 组件库.Apache 冷不丁翻译

Apache HttpComponents 工具类 [ HttpUtil ]

pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</gr

Apache HttpComponents中的cookie匹配策略

*/--> pre.src {background-color: #292b2e; color: #b2b2b2;} pre.src {background-color: #292b2e; color: #b2b2b2;} pre.src {background-color: #292b2e; color: #b2b2b2;} pre.src {background-color: #292b2e; color: #b2b2b2;} pre.src {background-color: #292b

org.apache.commons.httpclient

org.apache.commons.httpclient 1 /** 2 * post 方法 3 * @param url 4 * @param params 5 * @return 6 */ 7 public static String post(String url, Object content, String encode) throws Exception { 8 9 byte[] responseBody = null; 10 HttpClient httpclient = new

httpClient使用中报错org.apache.commons.httpclient.HttpMethodBase - Going to buffer response body of large or unknown size.

在使用HttpClient发送请求,使用httpMethod.getResponseBodyAsString();时当返回值过大时会报错: org.apache.commons.httpclient.HttpMethodBase - Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended. 可以如下解决: 1 BufferedReade

java模拟http请求上传文件,基于Apache的httpclient

1.依赖 模拟http端的请求需要依赖Apache的httpclient,需要第三方JSON支持,项目中添加 <dependency> <groupId>org.apache</groupId> <artifactId>httpclient</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>

通过Apache的httpClient的post方式连接服务器

客户端的代码是: package lgx.java.test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; im