關于Java去連接HTTP地址的操作

jopen 8年前發布 | 9K 次閱讀 Java開發

使用HTTPClient進行操作,可以忽略SSL

/**
 * @author Kai
 * @Date 2015-7-28 19:47:16
 */
public class HTTPClient {

    //HTTP請求讀取超時時間
    private static final int SOCKET_TIME_OUT = 5000;
    //HTTP請求連接時間
    private static final int CONNECT_TIME_OUT = 5000;
    //請求重試次數
    private static final int RETRY_TIMES = 3;
    
     /**
     * 
     * @param address 請求地址
     * @param method  請求方式
     * @param params 請求參數
     * @param paramSendType 發送類型
     * @param cookies 設置cookies值發送
     * @return 
     */
    public String request(String address, String method, String params, String paramSendType, String cookies) {
        address = address.trim();
        CloseableHttpResponse closeableHttpResponse = null;
        if (SupportProtocol.HTTP_METHOD_GET.equalsIgnoreCase(method)) {
            closeableHttpResponse = this.GET(address, params, paramSendType, cookies);
        } else if (SupportProtocol.HTTP_METHOD_POST.equalsIgnoreCase(method)) {
            closeableHttpResponse = this.POST(address, params, paramSendType, cookies);
        } else if (SupportProtocol.HTTP_METHOD_PUT.equalsIgnoreCase(method)) {
            closeableHttpResponse = this.PUT(address, params, paramSendType, cookies);
        } else {
            closeableHttpResponse = this.POST(address, params, paramSendType, cookies);
        }

        return this.buildReponseMsg(closeableHttpResponse);
    }
    
    private CloseableHttpResponse PUT(String address, String params, String paramSendType, String cookies) {
        try {
            URI uri = URI.create(address);
            HttpPut httpPut = new HttpPut(uri);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
            httpPut.setConfig(requestConfig);

            if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {
                httpPut.setHeader("Content-Type", "application/json; charset=UTF-8");
                StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);
                httpPut.setEntity(entity);
            } else if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {
                httpPut.setHeader("Content-Type", "application/xml; charset=UTF-8");
                StringEntity entity = new StringEntity(params, ContentType.APPLICATION_XML);
                httpPut.setEntity(entity);
            } else {
                httpPut.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                StringEntity entity = new StringEntity(params, ContentType.APPLICATION_FORM_URLENCODED);
                httpPut.setEntity(entity);
            }

            if (StrUtil.isNotEmpty(cookies)) {
                httpPut.setHeader("Cookie", cookies);
            }

            CloseableHttpClient httpClient = HttpClients.createDefault();

            if (address.toLowerCase().startsWith("https")) {
                httpClient = this.createSSLClientDefault();
            }

            return httpClient.execute(httpPut);
        } catch (Exception ex) {
            LogUtil.error(ex);
        }
        return null;
    }

    private CloseableHttpResponse GET(String address, String params, String paramSendType, String cookies) {
        try {
            URI uri;
            if (EmptyUtil.isNotEmpty(params)) {
                uri = URI.create(String.format("%s?%s", address, params));
            } else {
                uri = URI.create(address);
            }

            HttpGet httpGet = new HttpGet(uri);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
            httpGet.setConfig(requestConfig);

            if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {
                httpGet.setHeader("Content-Type", "application/json; charset=UTF-8");
            } else if (SupportProtocol.SUPPORT_XML.equalsIgnoreCase(paramSendType)) {
                httpGet.setHeader("Content-Type", "application/xml; charset=UTF-8");
            } else {
                httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }

            if (StrUtil.isNotEmpty(cookies)) {
                httpGet.setHeader("Cookie", cookies);
            }
            CloseableHttpClient httpClient = HttpClients.createDefault();
            if (address.toLowerCase().startsWith("https")) {
                httpClient = this.createSSLClientDefault();
            }
            return httpClient.execute(httpGet);
        } catch (Exception ex) {
            LogUtil.error(ex);
        }
        return null;
    }

    private CloseableHttpResponse POST(String address, String params, String paramSendType, String cookies) {
        try {
            URI uri = URI.create(address);
            HttpPost httpPost = new HttpPost(uri);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
            httpPost.setConfig(requestConfig);

            if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {
                httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
                StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
            } else if (SupportProtocol.SUPPORT_XML.equalsIgnoreCase(paramSendType)) {
                httpPost.setHeader("Content-Type", "application/xml; charset=UTF-8");
                StringEntity entity = new StringEntity(params, ContentType.APPLICATION_XML);
                httpPost.setEntity(entity);
            } else {
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                StringEntity entity = new StringEntity(params, ContentType.APPLICATION_FORM_URLENCODED);
                httpPost.setEntity(entity);
            }

            if (StrUtil.isNotEmpty(cookies)) {
                httpPost.setHeader("Cookie", cookies);
            }

            CloseableHttpClient httpClient = HttpClients.createDefault();
            if (address.toLowerCase().startsWith("https")) {
                httpClient = this.createSSLClientDefault();
            }
            return httpClient.execute(httpPost);
        } catch (Exception ex) {
            LogUtil.error(ex);
        }
        return null;
    }

    private CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            return HttpClients.custom().setSSLSocketFactory(ssf).build();
        } catch (Exception e) {
            LogUtil.error(e.getMessage());
        }
        return HttpClients.createDefault();
    }

    private String buildReponseMsg(CloseableHttpResponse closeableHttpResponse) {
        if (closeableHttpResponse == null) {
            return null;
        }
        try {
            int code = closeableHttpResponse.getStatusLine().getStatusCode();
            String msg = EntityUtils.toString(closeableHttpResponse.getEntity());
            if (code == HttpStatus.SC_OK) {
                return msg;
            }
        } catch (Exception ex) {
            LogUtil.error(ex);
        }
        return null;
    }
}


使用URLConnection讀取數據,訪問HTTPS貌似有問題

package com.k.ctc.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

/**
 *
 * @author Kai
 */
public class Connector {

    public String GET(String address, Map<String, String> params) throws Exception {
        String param = this.buildParams(params);
        URL url = new URL(address + "?" + param);
        URLConnection conn = url.openConnection();
        return this.readData(conn);
    }

    public String GET(String address, String params) throws Exception {
        URL url = new URL(address + "?" + params);
        URLConnection conn = url.openConnection();
        return this.readData(conn);
    }

    public String POST(String address, Map<String, String> params) throws Exception {
        String param = this.buildParams(params);
        URL url = new URL(address);
        URLConnection conn = url.openConnection();
        this.postData(conn, param);
        return this.readData(conn);
    }

    public String POST(String address, String param) throws Exception {
        URL url = new URL(address);
        URLConnection conn = url.openConnection();
        this.postData(conn, param);
        return this.readData(conn);
    }

    private String buildParams(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            sb.append(param.getKey()).append("=");
            sb.append(URLEncoder.encode(param.getValue(), "UTF-8"));
            sb.append("&");
        }
        return sb.toString();
    }

    private void postData(final URLConnection conn, String requestData) throws Exception {
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(requestData);
        wr.flush();
        wr.close();
    }

    private String readData(final URLConnection conn) throws Exception {
        String responseData = "";
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = rd.readLine()) != null) {
            responseData += line;
        }
        responseData = new String(responseData.getBytes(), "UTF-8");
        rd.close();
        return responseData;
    }
}


做個代碼記錄 Maven引用

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore-nio</artifactId>
    <version>4.4</version>
</dependency>



來自: http://my.oschina.net/Kxvz/blog/599039

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!