1. 程式人生 > >java傳送HTTP和HTTPS請求

java傳送HTTP和HTTPS請求

HTTP請求沒什麼好說的,如果您將請求HTTPS請求,在開啟連結前請先繞過SSL驗證,如下為繞過驗證的工具類

package com.weavernorth.httpconn;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
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; /** * 在請求HTTPS協議的URL遇到SSL證書驗證不通過時可以藉助此SslUtils繞過SSL驗證 * @author Dylan * */ public class SslUtils { private static void trustAllHttpsCertificates() throws Exception { TrustManager[] trustAllCerts = new
TrustManager[1]; TrustManager tm = new miTM(); trustAllCerts[0] = tm; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } static class miTM implements TrustManager,X509TrustManager { public
X509Certificate[] getAcceptedIssuers() { return null; } public boolean isServerTrusted(X509Certificate[] certs) { return true; } public boolean isClientTrusted(X509Certificate[] certs) { return true; } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { return; } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { return; } } /** * 忽略HTTPS請求的SSL證書,必須在openConnection之前呼叫 * @throws Exception */ public static void ignoreSsl() throws Exception{ HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv); } }

請求HTTP

package com.weavernorth.httpconn;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.weavernorth.util.FileUtil;
/**
 * 上傳附件到泛微系統
 * @author Dylan
 *
 */
public class HttpURLConnrctionToFile {

    public static String uploadFile(String uploadUrl, String file) {  
        byte[] bbyte = FileUtil.File2byte(file);
        String end = "\r\n";  
        String twoHyphens = "--";  
        String boundary = "---------------------------Dylan";  
        try {  
            URL url = new URL(uploadUrl);  
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();  
            httpURLConnection.setDoInput(true);  
            httpURLConnection.setDoOutput(true);  
            httpURLConnection.setUseCaches(false);  
            httpURLConnection.setRequestMethod("POST");  
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");  
            httpURLConnection.setRequestProperty("Charset", "UTF-8");  
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);  

            String name = new File(file).getName();
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());  
            dos.writeBytes(twoHyphens + boundary + end);  
            dos.writeBytes("Content-Disposition: form-data; name=\"file1\"; filename=\""+new String(name.getBytes("UTF-8"), "ISO_8859_1")+"\"" + end);  
            dos.writeBytes("Content-Type: application/octet-stream;" + end);
            dos.writeBytes(end);  
            dos.write(bbyte);  
            dos.writeBytes(end);  
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);  
            dos.flush();  

            // 讀取伺服器返回結果  
            InputStream is = httpURLConnection.getInputStream();  
            InputStreamReader isr = new InputStreamReader(is, "utf-8");  
            BufferedReader br = new BufferedReader(isr);  
            String result = br.readLine();  
            System.out.println("response" + result);  
            is.close();  
            return  result;  

        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return "";  
    }



}

請求HTTPS

package com.weavernorth.httpconn;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.weavernorth.util.FileUtil;
import sun.misc.BASE64Decoder;
import weaver.conn.RecordSet;
import weaver.general.Util;

/**
 * 利用 HttpsURLConnection傳送 HTTP或者HTTPS請求
 * 若涉及SSL證書驗證,必須在openConnection之前繞過驗證
 * 否則就會出現那個著名的異常No subject alternative names matching IP address ***.**.*.*** found
 * 請將請求頭的設定放在寫出快取資料之前,否則會提示連線提前終止的異常
 * @author Dylan
 */
public class HttpsURLConnectionUtil {

    public static StringBuffer doPut(String param,String filed) throws IOException, JSONException {  
        //查詢郵件模組附件地址
        RecordSet rs = new RecordSet();
        //真實路徑
        String strFilerealpath = "";
        //查詢郵件附件相關資訊
        rs.executeSql("select filename,filerealpath,filesize from mailresourcefile where id = '" + filed + "'");
        if(rs.next()){
            strFilerealpath = Util.null2String(rs.getString("filerealpath"));
        }
        // 資料處理 轉換JSON物件
        JSONObject jsonParams;
        JSONArray arrDetail = null;
        try {
            jsonParams = new JSONObject(param);
            //strAuthrequest為HTTP的PUT請求中的請求協議配置項,為陣列型別
            String strAuthrequest = jsonParams.getString("authrequest");
            //請求協議配置項
            arrDetail = new JSONArray(strAuthrequest);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        //繞過SSL驗證
        try {
            SslUtils.ignoreSsl();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        //儲存響應資料
        StringBuffer sbuffer=null;
        System.out.println(arrDetail.getString(1));
        URL uri = new URL(arrDetail.getString(1));  
        HttpsURLConnection conn = (HttpsURLConnection) uri.openConnection(); 
        conn.setDoInput(true);// 允許輸入  
        conn.setDoOutput(true);// 允許輸出  
        conn.setUseCaches(false); // 不允許使用快取  
        conn.setRequestMethod(arrDetail.getString(0));//設定請求方式
        if (arrDetail != null) {
            for (int i = 2; i < arrDetail.length(); i++) {
                try {
                    String strVal = arrDetail.getString(i);
                    String[] split = strVal.split(":");
                    String substring = strVal.substring(strVal.indexOf(split[0]) + split[0].length() + 2, strVal.length());
                    //設定請求頭
                    conn.setRequestProperty(split[0], substring);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("請求頭設定完畢");

        }
        conn.setReadTimeout(10000);//設定讀取超時時間          
        conn.setConnectTimeout(10000);//設定連線超時時間           
        conn.connect();
        OutputStream out = conn.getOutputStream();//向物件輸出流寫出資料,這些資料將存到記憶體緩衝區中          
        File file = new File(strFilerealpath);
        //判斷檔案是否存在
        if (file.exists()) {
            System.out.println("上傳雲盤的檔案存在!");
            out.write(FileUtil.File2byte(strFilerealpath));
            out.flush();
            // 關閉流物件,此時,不能再向物件輸出流寫入任何資料,先前寫入的資料存在於記憶體緩衝區中
            out.close();
            System.out.println("寫出完畢");
        }else{
            System.out.println("需要上傳雲盤的檔案不存在!");
        }
        sbuffer = new StringBuffer(conn.getResponseCode() + "");
        // 讀取響應
        // if (conn.getResponseCode()==200){
        // 從伺服器獲得一個輸入流
        InputStreamReader inputStream = new InputStreamReader(
                conn.getInputStream());// 呼叫HttpURLConnection連線物件的getInputStream()函式,
                                        // 將記憶體緩衝區中封裝好的完整的HTTP請求電文傳送到服務端。
        BufferedReader reader = new BufferedReader(inputStream);
        String lines;
        sbuffer = new StringBuffer("");
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "UTF-8");
            sbuffer.append(lines);
        }
        reader.close();
        System.out.println(sbuffer);
        // 斷開連線
        conn.disconnect();

        return sbuffer;    



    }  
    // base64解密
    public static String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}