android网络请求工具类

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();
		}
	}
}

  

时间: 2024-11-06 08:02:44

android网络请求工具类的相关文章

网络请求工具类WebServiceUtils

如果对WebService一无所知的话,建议先看看这两篇博客,对你WebService很有帮助. http://blog.csdn.NET/eyu8874521/article/details/9125987 http://blog.csdn.net/xiaanming/article/details/16871117 本人也是菜鸟一名,WebService已经是很老的技术了,但现在仍有使用,刚开始接触的时候,是无从入手呀,看了上面几篇文章以后,渐渐的会使用了,这里感谢网上开源的作者和文章,网上

基于AFNetworking封装的网络请求工具类

前提,导入AFNetworking框架 关于修改AFN源码:通常序列化时做对text/plan等的支持时,可以一劳永逸的修改源代码,在acceptableContentTypes中修改即可. GGRequest.h 1 #import <Foundation/Foundation.h> 2 3 @interface GGRequest : NSObject 4 /** 5 * 网络请求方法 6 * 7 * @param url 将要访问的链接 8 * @param param 传入的参数 9

Java网络请求工具类(依赖:org.apache.http;注:HttpClient 4.4,HttpCore 4.4)

到此处可以去下载依赖包:http://hc.apache.org/downloads.cgi 1 import java.util.List; 2 3 import org.apache.http.HttpStatus; 4 import org.apache.http.NameValuePair; 5 import org.apache.http.client.config.RequestConfig; 6 import org.apache.http.client.entity.UrlEnc

android 网络判断工具类(APN+WIFI)

public class NetWorkHelper { private static String LOG_TAG = "NetWorkHelper"; public static Uri uri = Uri.parse("content://telephony/carriers"); /** * 判断是否有网络连接 */ public static boolean isNetworkAvailable(Context context) { Connectivit

Volley网络请求框架简析——Android网络请求框架(三)

题记-- 人来到这个世界上,只有两件事情,生与死, 一件事完了,另一件事还急什么? 有缘而来,无缘而去, 识自本心,见自本性 不起妄缘,无心无为 自由自在,动静自如 冷暖自知,则是修行 1.初始化一个消息请求队列以及网络请求工具类对象 /** * Created by androidlongs on 16/7/1. * 网络请求访问框架 */ public class VollyRequestUtils { /** * Volley框架使用工具类对象 */ private static Voll

Android 网络请求json数据,解析json数据,生成对应的java bean类一步到位,快速开发

Android 网络请求一般都涉及到图片和JSON数据,怎样快速的请求网络JSON数据,解析JSON数据,并且一步生成自己想要的Java bean实体类?这个涉及到Android 开发效率的问题.由于接触Android 网络这方面比较多,自然就找到一些好的方法来快速开发Android 网络模块的相关内容,接下来就为大家揭晓 一步快速请求,解析JSON 数据生成对应的Java bean实体类的方法. 注:我们先把思路讲解下吧: 1.网络请求JSON数据代码可以自己写,当然我还是推荐使用网络上开源的

我的Android进阶之旅------&gt;Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEn

基于Android Volley的网络请求工具

基于Android Volley的网络请求工具. 一.说明 AndroidVolley,Android Volley核心库及扩展工程.AndroidVolleySample,网络请求工具示例工程.Release,jar包.直接下载 二.Volley基本处理流程: 1.应用初始化Volley.2.Volley创建一个RequestQueue.NetworkDispatcher组及Network.3.RequestQueue即一个Request队列,RequestQueue会创建一个Executor

【Java&amp;Android开源库代码剖析】のandroid-async-http(如何设计一个优雅的Android网络请求框架,同时支持同步和异步请求)开篇

在<[Java&Android开源库代码剖析]のandroid-smart-image-view>一文中我们提到了android-async-http这个开源库,本文正式开篇来详细介绍这个库的实现,同时结合源码探讨如何设计一个优雅的Android网络请求框架.做过一段时间Android开发的同学应该对这个库不陌生,因为它对Apache的HttpClient API的封装使得开发者可以简洁优雅的实现网络请求和响应,并且同时支持同步和异步请求. 网络请求框架一般至少需要具备如下几个组件:1