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中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。
Android使用java,对于Http协议的基本功能由两种实现方案:
1,使用JDK的java.net包下的HttpURLConnection
2.使用Apache的HttpClie
Android SDK中集成了Apache的HttpClient模块,也即说Android上两种方法都能用。
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方式
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(); } }
DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(urlencode(params));
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>} }
mHttpEntity.getContent();
mHttpEntity = new UrlEncodedFormEntity(temparams, DEF_CHATSET); mHttpPost.setEntity(mHttpEntity);同样是对传入的params做了加密处理。
mHttpClient.execute(mHttpPost);