HttpUtils 封裝類

做爲一個web開發人員,對Http 請求,並不陌生。有時候,咱們請求的時候,須要使用代碼實現,通常狀況,咱們使用Apache Jakarta Common 下的子項目.的HttpClient.java

但是我發現,在開發過成,不少狀況,咱們使用的功能,並不須要,想象中的須要HttpClient 的不少特性。並且,須要引用jar 。這邊咱們使用Java jdk自帶的HttpsURLConnection.android

並且,這個能夠遷移到android項目封裝成一個HttpUtils 方法。代碼以下:web

package com.xuanyuan.utils.http;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

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


/**
 * HttpUtils幫助類 
 * User: PunkLin林克澎
 * Email: lentr@sina.cn
 * Date: 2017-04-04
 */
public class HttpUtils {
	
	
	private static Charset charset=Charset.defaultCharset();
	private static final String TAG = "HttpUtils";
	//連接超時
	private static final int mReadTimeOut = 1000 * 10; // 10秒
	//連接超時
	private static final int mConnectTimeOut = 1000 * 5; // 5秒
	private static final String CHAR_SET = charset.displayName();
	
	
	private static final int mRetry = 2; // 默認嘗試訪問次數
	
	/**
	 * 處理訪問字符串處理
	 * @param params
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private static String buildParams(Map<String,? extends Object> params) throws UnsupportedEncodingException{
		if(params ==null || params.isEmpty()){
			return null;
		}
		StringBuilder builder = new StringBuilder();
		for (Map.Entry<String, ? extends Object> entry : params.entrySet()) {
			if (entry.getKey() != null && entry.getValue() != null)
				builder.append(entry.getKey().trim()).append("=")
						.append(URLEncoder.encode(entry.getValue().toString(), CHAR_SET)).append("&");
		}
		if(builder.charAt(builder.length()-1)=='&'){
			builder.deleteCharAt(builder.length()-1);
		}
		return builder.toString();
	}
	
	
	/**
	 * 無參數的Get訪問
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String get(String url) throws Exception {
		return get(url, null);
	}

	/**
	 * 有參數的Get 訪問
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String get(String url, Map<String, ? extends Object> params) throws Exception {
		return get(url, params, null);
	}

	/**
	 * 含有報文頭的Get請求
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 * @throws Exception
	 */
	public static String get(String url, Map<String, ? extends Object> params, Map<String, String> headers) throws Exception {
		if (url == null || url.trim().length() == 0) {
			throw new Exception(TAG + ": url is null or empty!");
		}

		if (params != null && params.size() > 0) {
			if (!url.contains("?")) {
				url += "?";
			}
			if (url.charAt(url.length() - 1) != '?') {
				url += "&";
			}
			url += buildParams(params);
		}

		return tryToGet(url, headers);
	}
	
	private static String tryToGet(String url,Map<String,String> headers) throws Exception{
		int tryTime = 0;
		Exception ex = null;
		while (tryTime < mRetry) {
			try {
				return doGet(url, headers);
			} catch (Exception e) {
				if (e != null)
					ex = e;
				tryTime++;
			}
		}
		if (ex != null)
			throw ex;
		else
			throw new Exception("未知網絡錯誤 ");
	}
	
	/**
	 * Get 請求實現方法 核心 
	 * @param strUrl
	 * @param headers
	 * @return
	 * @throws Exception
	 */
	private static String doGet(String strUrl, Map<String, String> headers) throws Exception {
		HttpURLConnection connection = null;
		InputStream stream = null;
		try {

			connection = getConnection(strUrl);
			configConnection(connection);
			if (headers != null && headers.size() > 0) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					connection.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}

			connection.setInstanceFollowRedirects(true);
			connection.connect();

			stream = connection.getInputStream();
			ByteArrayOutputStream obs = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			for (int len = 0; (len = stream.read(buffer)) > 0;) {
				obs.write(buffer, 0, len);
			}
			obs.flush();
			obs.close();
			stream.close();

			return new String(obs.toByteArray());
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
			if (stream != null) {
				stream.close();
			}
		}
	}
	
	/**
	 * Post 請求,無參數的請求
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String post(String url) throws Exception {
		return post(url, null);
	}

	/**
	 * Post 請求,帶參數的請求。
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String post(String url, Map<String, ? extends Object> params) throws Exception {
		return post(url, params, null);
	}

	/**
	 * Post 請求,帶參數的請求,請求報文的
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String post(String url, Map<String, ? extends Object> params, Map<String, String> headers)
			throws Exception {
		if (url == null || url.trim().length() == 0) {
			throw new Exception(TAG + ":url is null or empty!");
		}

		if (params != null && params.size() > 0) {
			return tryToPost(url, buildParams(params), headers);
		} else {
			return tryToPost(url, null, headers);
		}
	}

	public static String post(String url, String content, Map<String, String> headers) throws Exception {
		return tryToPost(url, content, headers);
	}

	
	private static String tryToPost(String url, String postContent, Map<String, String> headers) throws Exception {
		int tryTime = 0;
		Exception ex = null;
		while (tryTime < mRetry) {
			try {
				return doPost(url, postContent, headers);
			} catch (Exception e) {
				if (e != null)
					ex = e;
				tryTime++;
			}
		}
		if (ex != null)
			throw ex;
		else
			throw new Exception("未知網絡錯誤 ");
	}
	
	
	private static String doPost(String strUrl, String postContent, Map<String, String> headers) throws Exception {
		HttpURLConnection connection = null;
		InputStream stream = null;
		try {
			connection = getConnection(strUrl);
			configConnection(connection);
			if (headers != null && headers.size() > 0) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					connection.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);

			if (null != postContent && !"".equals(postContent)) {
				DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
				dos.write(postContent.getBytes(CHAR_SET));
				dos.flush();
				dos.close();
			}
			stream = connection.getInputStream();
			ByteArrayOutputStream obs = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			for (int len = 0; (len = stream.read(buffer)) > 0;) {
				obs.write(buffer, 0, len);
			}
			obs.flush();
			obs.close();
			return new String(obs.toByteArray());
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
			if (stream != null) {
				stream.close();
			}
		}
	}
	
	
	
	private static void configConnection(HttpURLConnection connection){
		if(connection==null){
			return;
		}
		
		connection.setReadTimeout(mReadTimeOut);
		connection.setConnectTimeout(mConnectTimeOut);
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
	}
	
	/**
	 * 根據輸入的請求地址判斷使用https 仍是使用http 獲取不一樣的HttpURLConnection.
	 * @param strUrl
	 * @return
	 * @throws Exception
	 */
	private static HttpURLConnection getConnection(String strUrl) throws Exception {
		if(strUrl == null){
			return null;
		}
		if(strUrl.toLowerCase().startsWith("https")){
			return getHttpsConnection(strUrl);
		}else{
			return getHttpConnection(strUrl);
		}
	}


	//獲取HTTP
	private static HttpURLConnection getHttpConnection(String urlStr) throws Exception {
		URL url =new URL(urlStr);
		HttpURLConnection conn=(HttpURLConnection) url.openConnection();
		return conn;
	}


	private static HttpURLConnection getHttpsConnection(String urlStr) throws Exception {
		URL url =new URL(urlStr);
		HttpsURLConnection conn=(HttpsURLConnection) url.openConnection();
		conn.setHostnameVerifier(hnv);
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		if(sslContext != null){
			TrustManager[] tm={xtm};
			sslContext.init(null, tm, null);
			SSLSocketFactory ssf =sslContext.getSocketFactory();
			conn.setSSLSocketFactory(ssf);
		}
		
		return conn;
	}
	
	private static X509TrustManager xtm = new X509TrustManager() {

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

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

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	};
	
	/**
	 * 用於主機名驗證的基接口
	 */
	private static HostnameVerifier hnv = new HostnameVerifier() {
		 //驗證主機名和服務器驗證方案的匹配是可接受的。 能夠接受返回true
		 public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};
}

 這樣,少了不少jar的引用。而且功能實現了 Https.服務器

相關文章
相關標籤/搜索