Java https請求

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/Eileen_crystal/article/details/52587232
java https請求,需要依賴包:



package com.xxx.sjf.utils.HttpsClientSendPost;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.HostNameResolver;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


/*
 *  * 
 */
public class HttpsClientSendPost {

    /*public static void main(String[] args) {
        String urlString = "https://open.ccchong.com/api/refreshToken";
        String output = new String(HttpClientSendPost.sendXMLDataByGet(urlString,"appkey=8AArM9016w3H26B5j1&appsecret=wp7j1K4880eAMmjo4s3Rtkq44l949u3p"));
        System.out.println(output);
    }*/


    private static DefaultHttpClient client;

    /**
     * 訪問https的網站
     * @param httpclient
     */
    private static void enableSSL(DefaultHttpClient httpclient) {
        //調用ssl  
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{truseAllManager}, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme https = new Scheme("https", sf, 443);
            httpclient.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重寫驗證方法,取消檢測ssl
     */
    private static TrustManager truseAllManager = new X509TrustManager() {

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub  

        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub  

        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub  
            return null;
        }

    };

    /**
     * HTTP Client Object,used HttpClient Class before(version 3.x),but now the
     * HttpClient is an interface
     */
    public static String sendXMLDataByGet(String url, String xml) {
        // 創建HttpClient實例
        if (client == null) {
        // Create HttpClient Object
            client = new DefaultHttpClient();
            enableSSL(client);
        }
        StringBuilder urlString = new StringBuilder();
        urlString.append(url);
        urlString.append("?");
        urlString.append(xml);
        System.out.println("url------"+urlString);
        String urlReq = urlString.toString();
        // 創建Get方法實例     
        HttpGet httpsgets = new HttpGet(urlReq);

        String strRep = "";
        try {
            HttpResponse response = client.execute(httpsgets);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                strRep = EntityUtils.toString(response.getEntity());
                // Do not need the rest
                httpsgets.abort();
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return strRep;
    }


    /**
     * Send a XML-Formed string to HTTP Server by post method
     *
     * @param url     the request URL string
     * @param xmlData XML-Formed string ,will not check whether this string is
     *                XML-Formed or not
     * @return the HTTP response status code ,like 200 represents OK,404 not
     * found
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String sendXMLDataByPost(String url, String xmlData)
            throws ClientProtocolException, IOException {
        if (client == null) {
            // Create HttpClient Object
            client = new DefaultHttpClient();
            enableSSL(client);
        }
        client.getParams().setParameter("http.protocol.content-charset",
                HTTP.UTF_8);
        client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
        client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
        client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,
                HTTP.UTF_8);

        // System.out.println(HTTP.UTF_8);
        // Send data by post method in HTTP protocol,use HttpPost instead of
        // PostMethod which was occurred in former version
        // System.out.println(url);
        HttpPost post = new HttpPost(url);
        post.getParams().setParameter("http.protocol.content-charset",
                HTTP.UTF_8);
        post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
        post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
        post.getParams()
                .setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);


        // Construct a string entity
        StringEntity entity = new StringEntity(getUTF8XMLString(xmlData), "UTF-8");
        entity.setContentType("text/xml;charset=UTF-8");
        entity.setContentEncoding("UTF-8");
        // Set XML entity
        post.setEntity(entity);
        // Set content type of request header
        post.setHeader("Content-Type", "text/xml;charset=UTF-8");
        // Execute request and get the response
        HttpResponse response = client.execute(post);
        HttpEntity entityRep = response.getEntity();
        String strrep = "";
        if (entityRep != null) {
            strrep = EntityUtils.toString(response.getEntity());
            // Do not need the rest    
            post.abort();
        }
        // Response Header - StatusLine - status code
        // statusCode = response.getStatusLine().getStatusCode();
        return strrep;
    }

    /**
     * Get XML String of utf-8
     *
     * @return XML-Formed string
     */
    public static String getUTF8XMLString(String xml) {
        // A StringBuffer Object
        StringBuffer sb = new StringBuffer();
        sb.append(xml);
        String xmString = "";
        try {
            xmString = new String(sb.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // return to String Formed
        return xmString.toString();
    }

    public static String sendPost(String url,String param ) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打開和URL之間的連接
            URLConnection conn = realUrl.openConnection();
            // 設置通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 發送POST請求必須設置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 獲取URLConnection對象對應的輸出流
//            out = new PrintWriter(conn.getOutputStream(),"utf-8");
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
            // 發送請求參數
            out.print(param);
            // flush輸出流的緩衝
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應
            /*in = new BufferedReader(new InputStreamReader(conn.getInputStream()));*/
            // 定義BufferedReader輸入流來讀取URL響應
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            while(in.readLine()!=null){
                line=in.readLine();
                result +=line;
            }
        } catch (Exception e) {
            System.out.println("發送 POST 請求出現異常!"+e);
            e.printStackTrace();
        }
        //使用finally塊來關閉輸出流、輸入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章