標籤:android blog http io ar os 使用 sp java
package com.example.util;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.ProtocolException;import java.net.URI;import java.net.URL;import java.net.URLEncoder;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.List;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.TrustManager;import javax.net.ssl.X509TrustManager;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.util.Log;/** * 網路連接輔助類 *項目名稱:xxxxxxxx * * @author zhangjie * */public class HttpUtil {private static final String TAG = "HttpUtil";/** 連線逾時 */private static final int TIME_OUT = 5 * 1000;/** * 發送post請求 * * @param strUrl * 網址路徑 * @param map * 請求的參數 * @return 返回請求的結果 */public static String executePost(String strUrl, Map<String, String> map) {String result = null;BufferedReader reader = null;try {HttpClient client = new DefaultHttpClient();// HttpPost連線物件HttpPost request = new HttpPost();request.setURI(new URI(strUrl));// 使用NameValuePair來儲存要傳遞的Post參數List<NameValuePair> postParameters = new ArrayList<NameValuePair>();if (null != map) {for (Map.Entry<String, String> entry : map.entrySet()) {Log.i(TAG, entry.getKey() + "=>" + entry.getValue());postParameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));}}// 設定字元集UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters, "utf-8");request.setEntity(formEntity);HttpResponse response = client.execute(request);// HttpStatus.SC_OK表示串連成功if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {Log.i(TAG, "串連成功,串連狀態代碼為:"+ response.getStatusLine().getStatusCode());reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));StringBuffer strBuffer = new StringBuffer("");String line = null;while ((line = reader.readLine()) != null) {strBuffer.append(line);}result = strBuffer.toString();Log.i(TAG, result);} else {Log.i(TAG, "串連失敗,串連狀態代碼為:"+ response.getStatusLine().getStatusCode());}} catch (Exception e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();reader = null;} catch (IOException e) {e.printStackTrace();}}}return result;}/** * 發送post請求 * * @param urlAddress * 請求的路徑 * @param map * 請求的參數 * @return 返回請求後的結果 * @throws AccessUrlException */public static String executeHttpPost(Context context, String urlAddress,Map<String, String> map) throws AccessUrlException,AccessTimeOutException {try {initSSL();} catch (KeyManagementException e1) {e1.printStackTrace();} catch (NoSuchAlgorithmException e1) {e1.printStackTrace();}SharedPreferences sharedPreferences = context.getSharedPreferences("YinYiTong", Context.MODE_PRIVATE);String result = null;URL url = null;HttpURLConnection connection = null;InputStreamReader in = null;try {url = new URL(urlAddress);connection = (HttpURLConnection) url.openConnection();connection.setConnectTimeout(TIME_OUT);connection.setDoInput(true);// 使用 URL串連進行輸入connection.setDoOutput(true);// 使用 URL串連進行輸出connection.setUseCaches(false);// 忽略緩衝connection.setRequestMethod("POST");connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");connection.setRequestProperty("Charset", "utf-8");// session idString sessionId = sharedPreferences.getString("sessionId", "");if (!(sessionId==null)) {connection.setRequestProperty("Cookie", sessionId);}StringBuilder params = new StringBuilder();// 設定參數if (null != map) {for (Map.Entry<String, String> entry : map.entrySet()) {Log.i(TAG, entry.getKey() + "=>" + entry.getValue());params.append(entry.getKey());params.append("=");params.append(URLEncoder.encode(entry.getValue(), "utf-8"));params.append("&");}}if (params.length() > 0)params.deleteCharAt(params.length() - 1);OutputStream outputStream = null;try {outputStream = connection.getOutputStream();} catch (Exception e) {Log.w(TAG, "訪問伺服器位址:" + urlAddress + "逾時.");throw new AccessTimeOutException("訪問伺服器位址:" + urlAddress+ "逾時.");}DataOutputStream dop = new DataOutputStream(outputStream);dop.write(params.toString().getBytes());dop.flush();dop.close();if (connection.getResponseCode() == HttpStatus.SC_OK) {Log.i(TAG, "connection status is 200");// 擷取返回結果in = new InputStreamReader(connection.getInputStream());BufferedReader bufferedReader = new BufferedReader(in);StringBuffer strBuffer = new StringBuffer();String line = null;while ((line = bufferedReader.readLine()) != null) {strBuffer.append(line);}result = strBuffer.toString();Log.i(TAG, result);// session id不同,重新設定String session_value = connection.getHeaderField("Set-Cookie");if (!(session_value==null)) {String[] sessionIds = session_value.split(";");Log.i(TAG, "sessionId=" + sessionIds[0]);if (null != sessionIds[0]&& !sessionIds[0].equalsIgnoreCase(sessionId)) {Editor editor = sharedPreferences.edit();editor.putString("sessionId", sessionIds[0]);editor.commit();}}} else {Log.w(TAG, "訪問伺服器異常,狀態代碼為:" + connection.getResponseCode());throw new AccessUrlException("訪問伺服器異常,狀態代碼為:"+ connection.getResponseCode());}} catch (MalformedURLException e) {Log.e(TAG, "[executeHttpPost]:", e);} catch (ProtocolException e) {Log.e(TAG, "[executeHttpPost]:", e);} catch (UnsupportedEncodingException e) {Log.e(TAG, "[executeHttpPost]:", e);} catch (IOException e) {Log.e(TAG, "[executeHttpPost]:", e);} finally {if (connection != null) {connection.disconnect();}if (in != null) {try {in.close();} catch (IOException e) {Log.e(TAG, "[executeHttpPost]InputStreamReader關閉異常:", e);}}}return result;}/** * 接受任何認證,不考慮認證發行者及所在主機情況 * * @throws NoSuchAlgorithmException * @throws KeyManagementException */public static void initSSL() throws NoSuchAlgorithmException,KeyManagementException {// Create a trust manager that does not validate certificate chainsTrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {public X509Certificate[] getAcceptedIssuers() {return null;}public void checkClientTrusted(X509Certificate[] certs,String authType) {// Trust always}public void checkServerTrusted(X509Certificate[] certs,String authType) {// Trust always}} };// Install the all-trusting trust managerSSLContext sc = SSLContext.getInstance("SSL");// Create empty HostnameVerifierHostnameVerifier hv = new HostnameVerifier() {public boolean verify(String arg0, SSLSession arg1) {return true;}};sc.init(null, trustAllCerts, new java.security.SecureRandom());HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());HttpsURLConnection.setDefaultHostnameVerifier(hv);}/** * 檢查網路連接 * * @param context * @return 有可用的接連返回true,否則返回false */public static boolean hasNetwork(Context context) {ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo workinfo = con.getActiveNetworkInfo();if (workinfo == null || !workinfo.isAvailable()) {Log.w(TAG, "當前無網路連接......");return false;}return true;}@SuppressWarnings("serial")public static class AccessUrlException extends Exception {public AccessUrlException() {super();}public AccessUrlException(String msg) {super(msg);}@Overridepublic String toString() {return super.toString();}}@SuppressWarnings("serial")public static class AccessTimeOutException extends Exception {public AccessTimeOutException() {super();}public AccessTimeOutException(String msg) {super(msg);}@Overridepublic String toString() {return super.toString();}}}
android網路請求工具類