HttpClientUtil

创建时间:2018/1/8 12:02
更新时间:2018/1/8 12:02
标签:http, util


import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.Hashtable;

public class HttpClientUtil {

    public static Hashtable postHttp(String uri, String s, Hashtable head) {
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        try {
            httpclient = getHttpClient(uri);
            HttpPost httppost = new HttpPost(uri);
            StringEntity body = new StringEntity(s, "utf-8");
            body.setContentEncoding("UTF-8");
            body.setContentType("text/html");
            httppost.setEntity(body);
            Enumeration en = head.keys();
            while (en.hasMoreElements()) {
                String ok = en.nextElement().toString();
                httppost.setHeader(ok, head.get(ok).toString());
            }
            response = httpclient.execute(httppost);
            return getHttpResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
            return new Hashtable();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Hashtable getHttp(String uri, Hashtable head) {
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        try {
            httpclient = getHttpClient(uri);
            HttpGet httpget = new HttpGet(uri);
            Enumeration en = head.keys();
            while (en.hasMoreElements()) {
                String ok = en.nextElement().toString();
                httpget.setHeader(ok, head.get(ok).toString());
            }
            response = httpclient.execute(httpget);
            return getHttpResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
            return new Hashtable();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static CloseableHttpClient getHttpClient(String uri) throws Exception {
        if (uri.contains("https:")) {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            httpClientBuilder.setSSLContext(sslContext);
            return httpClientBuilder.build();
        } else {
            return HttpClients.createDefault();
        }
    }

    private static Hashtable getHttpResponse(CloseableHttpResponse response) throws IOException {
        Hashtable ht = new Hashtable();
        ht.put("StatusCode", response.getStatusLine().getStatusCode());
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            ht.put("Entity", EntityUtils.toString(entity, "UTF-8"));
            for (Header hd : response.getAllHeaders()) {
                ht.put(hd.getName(), hd.getValue());
            }
        }
        return ht;
    }

    
    private void upload() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
            FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();

            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}