码迷,mamicode.com
首页 > 移动开发 > 详细

android网络请求工具类

时间:2014-11-24 19:10:25      阅读:283      评论:0      收藏:0      [点我收藏+]

标签: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 id
			String 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 chains
		TrustManager[] 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 manager
		SSLContext sc = SSLContext.getInstance("SSL");
		// Create empty HostnameVerifier
		HostnameVerifier 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);
		}

		@Override
		public String toString() {
			return super.toString();
		}
	}

	@SuppressWarnings("serial")
	public static class AccessTimeOutException extends Exception {
		public AccessTimeOutException() {
			super();
		}

		public AccessTimeOutException(String msg) {
			super(msg);
		}

		@Override
		public String toString() {
			return super.toString();
		}
	}
}

  

android网络请求工具类

标签:android   blog   http   io   ar   os   使用   sp   java   

原文地址:http://www.cnblogs.com/zhangjie9142/p/4119305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!