Android中Http请求

Android中的网络请求可以分为两种,HttpUrlConnection还有HttpClient,虽然Android中的网络请求框架很多,或许看起来让人觉得眼花缭乱,比如,vollery,Afinal等等。

但是万变不离其宗,这些框架都是根据这两个网络请求多次封装而成的。下面就主要介绍一下HttpUrlConnection和HttpClient。


Http(Hypertext Transfer Protocol)超文本传输协议,是一个基于请求/响应模式的无状态的协议,Http1.1版给出了持续连接的机制,客户端建立连接之后,可以发送多次请求,当不会再发送时再关闭连接。


HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。

除此之外,在Android中,androidSDK中集成了ApacheHttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。


Android使用java,对于Http协议的基本功能由两种实现方案:

1,使用JDK的java.net包下的HttpURLConnection

2.使用Apache的HttpClie


Android SDK中集成了Apache的HttpClient模块,也即说Android上两种方法都能用。

区别:

HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,
HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。


HttpClient的功能比较全,更加强大,而HttpURLConnection的功能比较原始和简单,但是性能更好


在Android2.x的版本中使用HttpURLConnection有bug,但是后来高级版本的Android已经将bug修复,并且做了一些进一步的优化工作,所以建议在高版本的Android中(android2.3)以后使用HttpURLConnection,低版本的仍使用HttpClient


再简单说一下POST和GET这两种方式吧:

get是从服务器上获取数据,post是向服务器传送数据

get传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制,但理论上IIS4中最大量为80KB,IIS5中为100KB

get安全性非常低,post安全性较高,但是执行效率却比Post方法好


所以建议:

get方式的安全性叫post方式要差些。包含机密信息的话,建议用post数据提交方式

在做数据查询时,建议用GET方式,在做数据添加,修改或删除时,建议用POST方式


HttpUrlConnection:

package com.zxx.httptest.normalnet;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 请求数据接口
 * 
 * @author zxx
 * 
 */
public class HttpUrlConnectionUtils {

	private static final String DEF_CHATSET = "UTF-8";
	private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
	private static int DEF_CONN_TIMEOUT = 30000;

	public static String doGET(String strUrl, Map params) throws Exception {
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		String rs = null;
		try {
			StringBuffer sb = new StringBuffer();
			strUrl = strUrl + "?" + urlencode(params);
			URL url = new URL(strUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("User-agent", userAgent);
			conn.setUseCaches(false);
			conn.setConnectTimeout(DEF_CONN_TIMEOUT);
			conn.setInstanceFollowRedirects(false);
			conn.connect();
			InputStream is = conn.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sb.append(strRead);
			}
			rs = sb.toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (reader != null) {
				reader.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return rs;
	}

	public static String doPOST(String strUrl, Map params) throws Exception {
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		String rs = null;
		try {
			StringBuffer sb = new StringBuffer();
			URL url = new URL(strUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.setRequestProperty("User-agent", userAgent);
			conn.setUseCaches(false);
			conn.setConnectTimeout(DEF_CONN_TIMEOUT);
			conn.setInstanceFollowRedirects(false);
			conn.connect();
			DataOutputStream out = new DataOutputStream(conn.getOutputStream());
			out.writeBytes(urlencode(params));
			InputStream is = conn.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sb.append(strRead);
			}
			rs = sb.toString();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (reader != null) {
				reader.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return rs;
	}

	// 将map型转为请求参数型
	private static String urlencode(Map<String, Object> params) {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		for (Map.Entry i : params.entrySet()) {
			try {
				sb.append(i.getKey()).append("=")
						.append(URLEncoder.encode(i.getValue() + "", "UTF-8"))
						.append("&");
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}

大致流程就是通过URL获取相应的HttpURLConnection然后通过urlencode这个方法将请求的url和所要筛选的参数进行拼接。然后放入到HttpURLConnection并开始向服务器请求,然后通过getInputStream方法获取请求的InputStream,最后通过封装到BufferedReader并转化相应的编码。对于得到的BufferedReader进行readLine,如果不为空的话,就说明读取到了数据,同时也表明请求成功。不要忘了在最后还是要释放该释放的资源。当然,这是get请求方式,如果是post的话大体上是差不多,不过有区别的是:
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
			out.writeBytes(urlencode(params));

需要做一下上述的处理,我的理解是可能是post方式为了安全性考虑吧,对拿到的最终的url进行了类似加密,或者再一次封装的操作,这一部分没有细究。不过大体应该是这个意思。


HttpClient:


package com.zxx.httptest.normalnet;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import org.apache.http.HttpEntity;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;


public class HttpClientUtils {


<span style="white-space:pre">	</span>private static final String DEF_CHATSET = "UTF-8";
<span style="white-space:pre">	</span>private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
<span style="white-space:pre">	</span>private static int DEF_CONN_TIMEOUT = 30000;


<span style="white-space:pre">	</span>public static String doGET(String urlAddress, Map params) {
<span style="white-space:pre">		</span>String getUrl = urlAddress + "?" + urlencode(params);
<span style="white-space:pre">		</span>HttpGet mHttpGet = new HttpGet(getUrl);
<span style="white-space:pre">		</span>HttpParams mHttpParams = mHttpGet.getParams();
<span style="white-space:pre">		</span>HttpConnectionParams.setStaleCheckingEnabled(mHttpParams, false);
<span style="white-space:pre">		</span>HttpConnectionParams.setConnectionTimeout(mHttpParams, 10 * 1000);// 设置请求超时10秒
<span style="white-space:pre">		</span>HttpConnectionParams.setSoTimeout(mHttpParams, 10 * 1000); // 设置等待数据超时10秒
<span style="white-space:pre">		</span>HttpConnectionParams.setSocketBufferSize(mHttpParams, 32 * 1024);
<span style="white-space:pre">		</span>mHttpParams.getParameter("true");


<span style="white-space:pre">		</span>HttpClient mHttpClient = new DefaultHttpClient(mHttpParams);
<span style="white-space:pre">		</span>try {
<span style="white-space:pre">			</span>HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
<span style="white-space:pre">			</span>if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
<span style="white-space:pre">				</span>HttpEntity mHttpEntity = mHttpResponse.getEntity();
<span style="white-space:pre">				</span>InputStream is = mHttpEntity.getContent();
<span style="white-space:pre">				</span>BufferedReader br = new BufferedReader(
<span style="white-space:pre">						</span>new InputStreamReader(is));
<span style="white-space:pre">				</span>String response = "";
<span style="white-space:pre">				</span>String readLine = null;
<span style="white-space:pre">				</span>while ((readLine = br.readLine()) != null) {
<span style="white-space:pre">					</span>response = response + readLine;
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>is.close();
<span style="white-space:pre">				</span>br.close();


<span style="white-space:pre">				</span>System.out.println("=====" + response);
<span style="white-space:pre">				</span>return response;
<span style="white-space:pre">			</span>} else {
<span style="white-space:pre">				</span>return "error";
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>} catch (Exception e) {
<span style="white-space:pre">			</span>// TODO: handle exception
<span style="white-space:pre">			</span>e.printStackTrace();
<span style="white-space:pre">			</span>return "exception";
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>public static String doPOST(String urlAddress, Map params) {
<span style="white-space:pre">		</span>HttpPost mHttpPost = new HttpPost(urlAddress);
<span style="white-space:pre">		</span>// List params = new ArrayList();
<span style="white-space:pre">		</span>// NameValuePair pair1 = new BasicNameValuePair("username",
<span style="white-space:pre">		</span>// username);
<span style="white-space:pre">		</span>// NameValuePair pair2 = new BasicNameValuePair("password",
<span style="white-space:pre">		</span>// password);
<span style="white-space:pre">		</span>// params.add(pair1);
<span style="white-space:pre">		</span>// params.add(pair2);
<span style="white-space:pre">		</span>HttpParams mHttpParams = mHttpPost.getParams();
<span style="white-space:pre">		</span>HttpConnectionParams.setStaleCheckingEnabled(mHttpParams, false);
<span style="white-space:pre">		</span>HttpConnectionParams.setConnectionTimeout(mHttpParams, 10 * 1000);// 设置请求超时10秒
<span style="white-space:pre">		</span>HttpConnectionParams.setSoTimeout(mHttpParams, 10 * 1000); // 设置等待数据超时10秒
<span style="white-space:pre">		</span>HttpConnectionParams.setSocketBufferSize(mHttpParams, 32 * 1024);
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>List temparams = new ArrayList();
<span style="white-space:pre">		</span>temparams = getParams(params);
<span style="white-space:pre">		</span>HttpEntity mHttpEntity;
<span style="white-space:pre">		</span>try {
<span style="white-space:pre">			</span>mHttpEntity = new UrlEncodedFormEntity(temparams, DEF_CHATSET);
<span style="white-space:pre">			</span>mHttpPost.setEntity(mHttpEntity);
<span style="white-space:pre">		</span>} catch (Exception e) {
<span style="white-space:pre">			</span>// TODO: handle exception
<span style="white-space:pre">			</span>e.printStackTrace();
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>HttpClient mHttpClient = new DefaultHttpClient(mHttpParams);
<span style="white-space:pre">		</span>try {
<span style="white-space:pre">			</span>HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
<span style="white-space:pre">			</span>// 连接成功
<span style="white-space:pre">			</span>if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
<span style="white-space:pre">				</span>HttpEntity httpEntity = mHttpResponse.getEntity();
<span style="white-space:pre">				</span>InputStream is = httpEntity.getContent();
<span style="white-space:pre">				</span>BufferedReader br = new BufferedReader(
<span style="white-space:pre">						</span>new InputStreamReader(is));
<span style="white-space:pre">				</span>String response = "";
<span style="white-space:pre">				</span>String readLine = null;
<span style="white-space:pre">				</span>while ((readLine = br.readLine()) != null) {
<span style="white-space:pre">					</span>response = response + readLine;
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>is.close();
<span style="white-space:pre">				</span>br.close();


<span style="white-space:pre">				</span>System.out.println("=====&&" + response);
<span style="white-space:pre">				</span>return response;
<span style="white-space:pre">			</span>} else {
<span style="white-space:pre">				</span>return "error";
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>} catch (Exception e) {
<span style="white-space:pre">			</span>// TODO: handle exception
<span style="white-space:pre">			</span>e.printStackTrace();
<span style="white-space:pre">			</span>return "exception";
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>// 将map型转为请求参数型
<span style="white-space:pre">	</span>private static String urlencode(Map<String, Object> params) {
<span style="white-space:pre">		</span>// TODO Auto-generated method stub
<span style="white-space:pre">		</span>StringBuilder sb = new StringBuilder();
<span style="white-space:pre">		</span>for (Map.Entry i : params.entrySet()) {
<span style="white-space:pre">			</span>try {
<span style="white-space:pre">				</span>sb.append(i.getKey())
<span style="white-space:pre">						</span>.append("=")
<span style="white-space:pre">						</span>.append(URLEncoder.encode(i.getValue() + "",
<span style="white-space:pre">								</span>DEF_CHATSET)).append("&");
<span style="white-space:pre">			</span>} catch (Exception e) {
<span style="white-space:pre">				</span>// TODO: handle exception
<span style="white-space:pre">				</span>e.printStackTrace();
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>return sb.toString();
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>private static List getParams(Map<String, Object> params) {


<span style="white-space:pre">		</span>List result = new ArrayList();
<span style="white-space:pre">		</span>for (Map.Entry i : params.entrySet()) {
<span style="white-space:pre">			</span>result.add(new BasicNameValuePair((String) i.getKey(), (String) i
<span style="white-space:pre">					</span>.getValue()));
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>return result;
<span style="white-space:pre">	</span>}
}

大致流程关于GET:
会先申明HttpGet,并将相应的请求url装载进去,还可以得到其params进行相应的请求设置,并一起装载到HttpClient中去,通过execute方法开始对请求做处理,当然方法返回的是一个HttpResponse对象,拿到这个对象就好说了,因为HttpClient内部做了一系列的封装,所以处理起来也很方便,我们可以通过拿到相应HttpResponse的getStatusCode的请求码,并对此作判断。返回200也就表示请求成功。然后就可以过去HttpResponse.getEntity的请求结果实体了,
mHttpEntity.getContent();

返回的当然是InputStream,拿到这个就好办了,也就和上面的HttpURLConnection的处理方式是一样的。通过BufferedReader做相应的封装转化得到response吧。

同样还有post方式,只是注意一下下面一点:
mHttpEntity = new UrlEncodedFormEntity(temparams, DEF_CHATSET);
			mHttpPost.setEntity(mHttpEntity);
同样是对传入的params做了加密处理。
mHttpClient.execute(mHttpPost);

处理请求。接下来的操作都是一样的。见代码。

上面的代码是可以直接当作工具类来使用的。如果有什么说的不对的还望指出哈,共同交流进步。

你可能感兴趣的:(网络,互联网,http协议)