android客戶端與服務端互動的三種方式

在南京看海發表於2016-09-08
android客戶端向伺服器通訊一般有以下選擇: 1.傳統的java.net.HttpURLConnection類 2.apache的httpClient框架(已納入android.jar中,可直接使用) 3.github上的開源框架async-http(基於httpClient) ---------------------------------------------------------------------------------- 下面分別記錄這三種方式的使用,
傳統方式:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/**
     * 以get方式向服務端傳送請求,並將服務端的響應結果以字串方式返回。如果沒有響應內容則返回空字串
     *
     * @param url 請求的url地址
     * @param params 請求引數
     * @param charset url編碼採用的碼錶
     * @return
     */
    public static String getDataByGet(String url,Map<string,string> params,String charset)
    {
        if(url == null)
        {
            return ;
        }
        url = url.trim();
        URL targetUrl = null;
        try
        {
            if(params == null)
            {
                targetUrl = new URL(url);
            }
            else
            {
                StringBuilder sb = new StringBuilder(url+?);
                for(Map.Entry<string,string> me : params.entrySet())
                {
//                    解決請求引數中含有中文導致亂碼問題
                    sb.append(me.getKey()).append(=).append(URLEncoder.encode(me.getValue(),charset)).append(&);
                }
                sb.deleteCharAt(sb.length()-1);
                targetUrl = new URL(sb.toString());
            }
            Log.i(TAG,get:url----->+targetUrl.toString());//列印log
            HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
            conn.setConnectTimeout(3000);
            conn.setRequestMethod(GET);
            conn.setDoInput(true);
            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK)
            {
                return stream2String(conn.getInputStream(),charset);
            }
        } catch (Exception e)
        {
            Log.i(TAG,e.getMessage());
        }
        return ;
/**
     *  以post方式向服務端傳送請求,並將服務端的響應結果以字串方式返回。如果沒有響應內容則返回空字串
     * @param url 請求的url地址
     * @param params 請求引數
     * @param charset url編碼採用的碼錶
     * @return
     */
    public static String getDataByPost(String url,Map<string,string> params,String charset)
    {
        if(url == null)
        {
            return ;
        }
        url = url.trim();
        URL targetUrl = null;
        OutputStream out = null;
        try
        {
            targetUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
            conn.setConnectTimeout(3000);
            conn.setRequestMethod(POST);
            conn.setDoInput(true);
            conn.setDoOutput(true);
             
            StringBuilder sb = new StringBuilder();
            if(params!=null && !params.isEmpty())
            {
                for(Map.Entry<string,string> me : params.entrySet())
                {
//                    對請求資料中的中文進行編碼
                    sb.append(me.getKey()).append(=).append(URLEncoder.encode(me.getValue(),charset)).append(&);
                }
                sb.deleteCharAt(sb.length()-1);
            }
            byte[] data = sb.toString().getBytes();
            conn.setRequestProperty(Content-Type,application/x-www-form-urlencoded);
            conn.setRequestProperty(Content-Length, String.valueOf(data.length));
            out = conn.getOutputStream();
            out.write(data);
             
            Log.i(TAG,post:url----->+targetUrl.toString());//列印log
             
            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK)
            {
                return stream2String(conn.getInputStream(),charset);
            }
        } catch (Exception e)
        {
            Log.i(TAG,e.getMessage());
        }
        return ;
    }
/**
     * 將輸入流物件中的資料輸出到字串中返回
     * @param in
     * @return
     * @throws IOException
     */
    private static String stream2String(InputStream in,String charset) throws IOException
    {
        if(in == null)
            return ;
        byte[] buffer = new byte[1024];
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        int len = 0;
        while((len = in.read(buffer)) !=-1)
        {
            bout.write(buffer, 0, len);
        }
        String result = new String(bout.toByteArray(),charset);
        in.close();
        return result;
    }</string,string></string,string></string,string></string,string>
使用httpClient:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package cn.edu.chd.httpclientdemo.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.NameValuePair;
import org.apache.http.StatusLine;
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 android.util.Log;
/**
 * @author Rowand jj
 *
 *http工具類,傳送get/post請求
 */
public final class HttpUtils
{
    private static final String TAG = HttpUtils;
    private static final String CHARSET = utf-8;
    private HttpUtils(){}
    /**
     * 以get方式向指定url傳送請求,將響應結果以字串方式返回
     * @param uri
     * @return 如果沒有響應資料返回null
     */
    public static String requestByGet(String url,Map<string,string> data)
    {
        if(url == null)
            return null;
//        構建預設http客戶端物件
        HttpClient client = new DefaultHttpClient();
        try
        {
//            拼裝url,並對中文進行編碼
            StringBuilder sb = new StringBuilder(url+?);
            if(data != null)
            {
                for(Map.Entry<string,string> me : data.entrySet())
                {
                    sb.append(URLEncoder.encode(me.getKey(),CHARSET)).append(=).append(URLEncoder.encode(me.getValue(),utf-8)).append(&);
                }
                sb.deleteCharAt(sb.length()-1);
            }
            Log.i(TAG, [get]--->uri:+sb.toString());
//            建立一個get請求
            HttpGet get = new HttpGet(sb.toString());
//            執行get請求,獲取http響應
            HttpResponse response = client.execute(get);
//            獲取響應狀態行
            StatusLine statusLine = response.getStatusLine();
            //請求成功
            if(statusLine != null && statusLine.getStatusCode() == 200)
            {
//                獲取響應實體
                HttpEntity entity = response.getEntity();
                if(entity != null)
                {
                    return readInputStream(entity.getContent());
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 以post方式向指定url傳送請求,將響應結果以字串方式返回
     * @param url
     * @param data 以鍵值對形式表示的資訊
     * @return
     */
    public static String requestByPost(String url,Map<string,string> data)
    {
        if(url == null)
            return null;
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        List<namevaluepair> params = null;
        try
        {
            Log.i(TAG, [post]--->uri:+url);
            params = new ArrayList<namevaluepair>();
            if(data != null)
            {
                for(Map.Entry<string,string> me : data.entrySet())
                {
                    params.add(new BasicNameValuePair(me.getKey(),me.getValue()));
                }
            }
//            設定請求實體
            post.setEntity(new UrlEncodedFormEntity(params,CHARSET));
//            獲取響應資訊
            HttpResponse response = client.execute(post);
            StatusLine statusLine = response.getStatusLine();
            if(statusLine!=null && statusLine.getStatusCode()==200)
            {
                HttpEntity entity = response.getEntity();
                if(entity!=null)
                {
                    return readInputStream(entity.getContent());
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
     
    /**
     * 將流中的資料寫入字串返回
     * @param is
     * @return
     * @throws IOException
     */
    private static String readInputStream(InputStream is) throws IOException
    {
        if(is == null)
            return null;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while((len = is.read(buf))!=-1)
        {
            bout.write(buf, 0, len);
        }
        is.close();
        return new String(bout.toByteArray());
    }
    /**
     * 將流中的資料寫入字串返回,以指定的編碼格式
     * 【如果服務端返回的編碼不是utf-8,可以使用此方法,將返回結果以指定編碼格式寫入字串】
     * @param is
     * @return
     * @throws IOException
     */
    private static String readInputStream(InputStream is,String charset) throws IOException
    {
        if(is == null)
            return null;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while((len = is.read(buf))!=-1)
        {
            bout.write(buf, 0, len);
        }
        is.close();
        return new String(bout.toByteArray(),charset);
    }
}</string,string></namevaluepair></namevaluepair></string,string></string,string></string,string>
3.使用async-http框架,這個如果使用的話需要匯入框架的jar包或者把原始碼拷到工程下: 這個框架的好處是每次請求會開闢子執行緒,不會拋networkonmainthread異常,另外處理器類繼承了Handler類,所以可以在裡面更改UI。 注:這裡使用的是最新的1.4.4版。 ·
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
     * 使用非同步http框架傳送get請求
     * @param path get路徑,中文引數需要編碼(URLEncoder.encode)
     */
    public void doGet(String path)
    {
        AsyncHttpClient httpClient = new AsyncHttpClient();
        httpClient.get(path, new AsyncHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
            {
                if(statusCode == 200)
                {
                    try
                    {
//                        此處應該根據服務端的編碼格式進行編碼,否則會亂碼
                        tv_show.setText(new String(responseBody,utf-8));
                    } catch (UnsupportedEncodingException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    /**
     * 使用非同步http框架傳送get請求
     * @param path
     */
    public void doPost(String path)
    {
        AsyncHttpClient httpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put(paper,中文);//value可以是流、檔案、物件等其他型別,很強大!!
        httpClient.post(path, params, new AsyncHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
            {
                if(statusCode == 200)
                {
                    tv_show.setText(new String(responseBody));
                }
            }
        });
    }

上面那個tv_show是一個TextView控制元件。




轉自 http://www.2cto.com/kf/201402/278147.html

相關文章