Android客戶端與服務端交互的三種方式

android客戶端向服務器通信一般有以下選擇:

 1.傳統的java.net.HttpURLConnection類 

2.apache的httpClient框架(已納入android.jar中,可直接使用)

 3.github上的開源框架async-http(基於httpClient)

001./**
002.* 以get方式向服務端發送請求,並將服務端的響應結果以字符串方式返回。如果沒有響應內容則返回空字符串
003.*
004.* @param url 請求的url地址
005.* @param params 請求參數
006.* @param charset url編碼採用的碼錶
007.* @return
008.*/
009.public static String getDataByGet(String url,Map<String,String> params,String charset)
010.{
011.if(url == null)
012.{
013.return "";
014.}
015.url = url.trim();
016.URL targetUrl = null;
017.try
018.{
019.if(params == null)
020.{
021.targetUrl = new URL(url);
022.}
023.else
024.{
025.StringBuilder sb = new StringBuilder(url+"?");
026.for(Map.Entry<String,String> me : params.entrySet())
027.{
028.//                    解決請求參數中含有中文導致亂碼問題
029.sb.append(me.getKey()).append("=").append(URLEncoder.encode(me.getValue(),charset)).append("&");
030.}
031.sb.deleteCharAt(sb.length()-1);
032.targetUrl = new URL(sb.toString());
033.}
034.Log.i(TAG,"get:url----->"+targetUrl.toString());//打印log
035.HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
036.conn.setConnectTimeout(3000);
037.conn.setRequestMethod("GET");
038.conn.setDoInput(true);
039.int responseCode = conn.getResponseCode();
040.if(responseCode == HttpURLConnection.HTTP_OK)
041.{
042.return stream2String(conn.getInputStream(),charset);
043.}
044.catch (Exception e)
045.{
046.Log.i(TAG,e.getMessage());
047.}
048.return "";
049./**
050.*  以post方式向服務端發送請求,並將服務端的響應結果以字符串方式返回。如果沒有響應內容則返回空字符串
051.* @param url 請求的url地址
052.* @param params 請求參數
053.* @param charset url編碼採用的碼錶
054.* @return
055.*/
056.public static String getDataByPost(String url,Map<String,String> params,String charset)
057.{
058.if(url == null)
059.{
060.return "";
061.}
062.url = url.trim();
063.URL targetUrl = null;
064.OutputStream out = null;
065.try
066.{
067.targetUrl = new URL(url);
068.HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
069.conn.setConnectTimeout(3000);
070.conn.setRequestMethod("POST");
071.conn.setDoInput(true);
072.conn.setDoOutput(true);
073. 
074.StringBuilder sb = new StringBuilder();
075.if(params!=null && !params.isEmpty())
076.{
077.for(Map.Entry<String,String> me : params.entrySet())
078.{
079.//                    對請求數據中的中文進行編碼
080.sb.append(me.getKey()).append("=").append(URLEncoder.encode(me.getValue(),charset)).append("&");
081.}
082.sb.deleteCharAt(sb.length()-1);
083.}
084.byte[] data = sb.toString().getBytes();
085.conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
086.conn.setRequestProperty("Content-Length", String.valueOf(data.length));
087.out = conn.getOutputStream();
088.out.write(data);
089. 
090.Log.i(TAG,"post:url----->"+targetUrl.toString());//打印log
091. 
092.int responseCode = conn.getResponseCode();
093.if(responseCode == HttpURLConnection.HTTP_OK)
094.{
095.return stream2String(conn.getInputStream(),charset);
096.}
097.catch (Exception e)
098.{
099.Log.i(TAG,e.getMessage());
100.}
101.return "";
102.}
103./**
104.* 將輸入流對象中的數據輸出到字符串中返回
105.* @param in
106.* @return
107.* @throws IOException
108.*/
109.private static String stream2String(InputStream in,String charset) throws IOException
110.{
111.if(in == null)
112.return "";
113.byte[] buffer = new byte[1024];
114.ByteArrayOutputStream bout = new ByteArrayOutputStream();
115.int len = 0;
116.while((len = in.read(buffer)) !=-1)
117.{
118.bout.write(buffer, 0, len);
119.}
120.String result = new String(bout.toByteArray(),charset);
121.in.close();
122.return result;
123.}
使用httpClient:
001.package cn.edu.chd.httpclientdemo.http;
002.import java.io.ByteArrayOutputStream;
003.import java.io.IOException;
004.import java.io.InputStream;
005.import java.net.URLEncoder;
006.import java.util.ArrayList;
007.import java.util.List;
008.import java.util.Map;
009.import org.apache.http.HttpEntity;
010.import org.apache.http.HttpResponse;
011.import org.apache.http.NameValuePair;
012.import org.apache.http.StatusLine;
013.import org.apache.http.client.HttpClient;
014.import org.apache.http.client.entity.UrlEncodedFormEntity;
015.import org.apache.http.client.methods.HttpGet;
016.import org.apache.http.client.methods.HttpPost;
017.import org.apache.http.impl.client.DefaultHttpClient;
018.import org.apache.http.message.BasicNameValuePair;
019.import android.util.Log;
020./**
021.* @author Rowand jj
022.*
023.*http工具類,發送get/post請求
024.*/
025.public final class HttpUtils
026.{
027.private static final String TAG = "HttpUtils";
028.private static final String CHARSET = "utf-8";
029.private HttpUtils(){}
030./**
031.* 以get方式向指定url發送請求,將響應結果以字符串方式返回
032.* @param uri
033.* @return 如果沒有響應數據返回null
034.*/
035.public static String requestByGet(String url,Map<String,String> data)
036.{
037.if(url == null)
038.return null;
039.//        構建默認http客戶端對象
040.HttpClient client = new DefaultHttpClient();
041.try
042.{
043.//            拼裝url,並對中文進行編碼
044.StringBuilder sb = new StringBuilder(url+"?");
045.if(data != null)
046.{
047.for(Map.Entry<String,String> me : data.entrySet())
048.{
049.sb.append(URLEncoder.encode(me.getKey(),CHARSET)).append("=").append(URLEncoder.encode(me.getValue(),"utf-8")).append("&");
050.}
051.sb.deleteCharAt(sb.length()-1);
052.}
053.Log.i(TAG, "[get]--->uri:"+sb.toString());
054.//            創建一個get請求
055.HttpGet get = new HttpGet(sb.toString());
056.//            執行get請求,獲取http響應
057.HttpResponse response = client.execute(get);
058.//            獲取響應狀態行
059.StatusLine statusLine = response.getStatusLine();
060.//請求成功
061.if(statusLine != null && statusLine.getStatusCode() == 200)
062.{
063.//                獲取響應實體
064.HttpEntity entity = response.getEntity();
065.if(entity != null)
066.{
067.return readInputStream(entity.getContent());
068.}
069.}
070.catch (Exception e)
071.{
072.e.printStackTrace();
073.}
074.return null;
075.}
076./**
077.* 以post方式向指定url發送請求,將響應結果以字符串方式返回
078.* @param url
079.* @param data 以鍵值對形式表示的信息
080.* @return
081.*/
082.public static String requestByPost(String url,Map<String,String> data)
083.{
084.if(url == null)
085.return null;
086.HttpClient client = new DefaultHttpClient();
087.HttpPost post = new HttpPost(url);
088.List<NameValuePair> params = null;
089.try
090.{
091.Log.i(TAG, "[post]--->uri:"+url);
092.params = new ArrayList<NameValuePair>();
093.if(data != null)
094.{
095.for(Map.Entry<String,String> me : data.entrySet())
096.{
097.params.add(new BasicNameValuePair(me.getKey(),me.getValue()));
098.}
099.}
100.//            設置請求實體
101.post.setEntity(new UrlEncodedFormEntity(params,CHARSET));
102.//            獲取響應信息
103.HttpResponse response = client.execute(post);
104.StatusLine statusLine = response.getStatusLine();
105.if(statusLine!=null && statusLine.getStatusCode()==200)
106.{
107.HttpEntity entity = response.getEntity();
108.if(entity!=null)
109.{
110.return readInputStream(entity.getContent());
111.}
112.}
113.catch (Exception e)
114.{
115.e.printStackTrace();
116.}
117.return null;
118.}
119. 
120./**
121.* 將流中的數據寫入字符串返回
122.* @param is
123.* @return
124.* @throws IOException
125.*/
126.private static String readInputStream(InputStream is) throws IOException
127.{
128.if(is == null)
129.return null;
130.ByteArrayOutputStream bout = new ByteArrayOutputStream();
131.int len = 0;
132.byte[] buf = new byte[1024];
133.while((len = is.read(buf))!=-1)
134.{
135.bout.write(buf, 0, len);
136.}
137.is.close();
138.return new String(bout.toByteArray());
139.}
140./**
141.* 將流中的數據寫入字符串返回,以指定的編碼格式
142.* 【如果服務端返回的編碼不是utf-8,可以使用此方法,將返回結果以指定編碼格式寫入字符串】
143.* @param is
144.* @return
145.* @throws IOException
146.*/
147.private static String readInputStream(InputStream is,String charset) throws IOException
148.{
149.if(is == null)
150.return null;
151.ByteArrayOutputStream bout = new ByteArrayOutputStream();
152.int len = 0;
153.byte[] buf = new byte[1024];
154.while((len = is.read(buf))!=-1)
155.{
156.bout.write(buf, 0, len);
157.}
158.is.close();
159.return new String(bout.toByteArray(),charset);
160.}
161.}
3.使用async-http框架,這個如果使用的話需要導入框架的jar包或者把源碼拷到工程下: 這個框架的好處是每次請求會開闢子線程,不會拋networkonmainthread異常,另外處理器類繼承了Handler類,所以可以在裏面更改UI。 注:這裏使用的是最新的1.4.4版。 ·
01./**
02.* 使用異步http框架發送get請求
03.* @param path get路徑,中文參數需要編碼(URLEncoder.encode)
04.*/
05.public void doGet(String path)
06.{
07.AsyncHttpClient httpClient = new AsyncHttpClient();
08.httpClient.get(path, new AsyncHttpResponseHandler(){
09.@Override
10.public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
11.{
12.if(statusCode == 200)
13.{
14.try
15.{
16.//                        此處應該根據服務端的編碼格式進行編碼,否則會亂碼
17.tv_show.setText(new String(responseBody,"utf-8"));
18.catch (UnsupportedEncodingException e)
19.{
20.e.printStackTrace();
21.}
22.}
23.}
24.});
25.}
26./**
27.* 使用異步http框架發送get請求
28.* @param path
29.*/
30.public void doPost(String path)
31.{
32.AsyncHttpClient httpClient = new AsyncHttpClient();
33.RequestParams params = new RequestParams();
34.params.put("paper","中文");//value可以是流、文件、對象等其他類型,很強大!!
35.httpClient.post(path, params, new AsyncHttpResponseHandler(){
36.@Override
37.public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
38.{
39.if(statusCode == 200)
40.{
41.tv_show.setText(new String(responseBody));
42.}
43.}
44.});
45.}
上面那個tv_show是一個TextView控件。

發佈了32 篇原創文章 · 獲贊 13 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章