1. 程式人生 > >Java網絡連接之HttpURLConnection、HttpsURLConnection

Java網絡連接之HttpURLConnection、HttpsURLConnection

main ons tee under system nbsp ini 對象 返回

工具類包含兩個方法: http請求、https請求

直接看代碼:

package com.jtools;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

/**
 * http工具類
 * @author json_wang
*/
public class HttpUtil {
	/**
	 * 發起http請求並獲取結果
	 * @param requestUrl 請求地址
	 * @param requestMethod 請求方式(GET、POST)
	 * @param outputStr 提交的數據       格式(例子:"name=name&age=age")  // 正文,正文內容其實跟get的URL中 ‘? ‘後的參數字符串一致
	 * @return json字符串(json格式不確定 可能是JSONObject,也可能是JSONArray,這裏用字符串,在controller裏再轉化)
	 */
	public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
		String resultStr = "";
		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 設置請求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);
			//HttpURLConnection是基於HTTP協議的,其底層通過socket通信實現。如果不設置超時(timeout),在網絡異常的情況下,可能會導致程序僵死而不繼續往下執行
			httpUrlConn.setConnectTimeout(30*1000);//30s超時
			httpUrlConn.setReadTimeout(10*1000);//10s超時

			/*
			//設置請求屬性    
			httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");     
			httpUrlConn.setRequestProperty("Charset", "UTF-8");
		    */
	        
			//HttpURLConnection的connect()函數,實際上只是建立了一個與服務器的tcp連接,並沒有實際發送http請求。
			//get方式需要顯式連接
			if ("GET".equalsIgnoreCase(requestMethod)){
				httpUrlConn.connect();
			}
			
			//這種post方式,隱式自動連接
			// 當有數據需要提交時
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 註意編碼格式,防止中文亂碼
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 將返回的輸入流轉換成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 釋放資源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			
			resultStr = buffer.toString();
		} catch (ConnectException ce) {
			System.out.println("server connection timed out.");
		} catch (Exception e) {
			System.out.println(requestUrl+" request error:\n"+e);
		}
		return resultStr;
	}
	
	/**
	 * 發起https請求並獲取結果
	 * 
	 * @param requestUrl 請求地址
	 * @param requestMethod 請求方式(GET、POST)
	 * @param outputStr 提交的數據       格式(例子:"name=name&age=age")  // 正文,正文內容其實跟get的URL中 ‘? ‘後的參數字符串一致
	 * @return json字符串(json格式不確定 可能是JSONObject,也可能是JSONArray,這裏用字符串,在controller裏再轉化)
	 */
	public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		String resultStr = "";
		StringBuffer buffer = new StringBuffer();
		try {
			// 創建SSLContext對象,並使用我們指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 從上述SSLContext對象中得到SSLSocketFactory對象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			
			// 設置請求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);
			//HttpURLConnection是基於HTTP協議的,其底層通過socket通信實現。如果不設置超時(timeout),在網絡異常的情況下,可能會導致程序僵死而不繼續往下執行
			httpUrlConn.setConnectTimeout(30*1000);//30s超時
			httpUrlConn.setReadTimeout(10*1000);//10s超時

			/*
			//設置請求屬性    
			httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");     
			httpUrlConn.setRequestProperty("Charset", "UTF-8");
		    */
	        
			//HttpURLConnection的connect()函數,實際上只是建立了一個與服務器的tcp連接,並沒有實際發送http請求。
			//get方式需要顯式連接
			if ("GET".equalsIgnoreCase(requestMethod)){
				httpUrlConn.connect();
			}
			
			//這種post方式,隱式自動連接
			// 當有數據需要提交時
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 註意編碼格式,防止中文亂碼
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 將返回的輸入流轉換成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 釋放資源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			
			resultStr = buffer.toString();
		} catch (ConnectException ce) {
			System.out.println("server connection timed out.");
		} catch (Exception e) {
			System.out.println(requestUrl+" request error:\n"+e);
		}
		return resultStr;
	}
	
	public static void main(String[] args) {
		System.out.println(httpRequest("https://www.zhihu.com/", "GET", null));
	}
	
}

輔助類:

package com.jtools;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

/**
 * 證書信任管理器(用於https請求)
 */
public class MyX509TrustManager implements X509TrustManager {

	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	}

	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	}

	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}
}

附:源代碼:https://github.com/JsonShare/JTools

PS:Java網絡連接之HttpURLConnection與HttpClient 區別及聯系 http://blog.csdn.net/wszxl492719760/article/details/8522714

Java網絡連接之HttpURLConnection、HttpsURLConnection