Android Http请求方法汇总

http://www.open-open.com/lib/view/open1351324240738.html

 

这篇文章主要实现了在Android中使用JDK的HttpURLConnection和Apache的HttpClient访问网络资源,服务端采用python+flask编写,使用Servlet太麻烦了。关于Http协议的相关知识,可以在网上查看相关资料。代码比较简单,就不详细解释了。

1. 使用JDK中HttpURLConnection访问网络资源

(1)get请求

01 public String executeHttpGet() {
02         String result = null;
03         URL url = null;
04         HttpURLConnection connection = null;
05         InputStreamReader in = null;
06         try {
07             url = new URL("http://10.0.2.2:8888/data/get/?token=alexzhou");
08             connection = (HttpURLConnection) url.openConnection();
09             in = new InputStreamReader(connection.getInputStream());
10             BufferedReader bufferedReader = new BufferedReader(in);
11             StringBuffer strBuffer = new StringBuffer();
12             String line = null;
13             while ((line = bufferedReader.readLine()) != null) {
14                 strBuffer.append(line);
15             }
16             result = strBuffer.toString();
17         catch (Exception e) {
18             e.printStackTrace();
19         finally {
20             if (connection != null) {
21                 connection.disconnect();
22             }
23             if (in != null) {
24                 try {
25                     in.close();
26                 catch (IOException e) {
27                     e.printStackTrace();
28                 }
29             }
30  
31         }
32         return result;
33     }

注意:因为是通过android模拟器访问本地pc服务端,所以不能使用localhost和127.0.0.1,使用127.0.0.1会访问模拟器自身。Android系统为实现通信将PC的IP设置为10.0.2.2

(2)post请求

01 public String executeHttpPost() {
02         String result = null;
03         URL url = null;
04         HttpURLConnection connection = null;
05         InputStreamReader in = null;
06         try {
07             url = new URL("http://10.0.2.2:8888/data/post/");
08             connection = (HttpURLConnection) url.openConnection();
09             connection.setDoInput(true);
10             connection.setDoOutput(true);
11             connection.setRequestMethod("POST");
12             connection.setRequestProperty("Content-Type""application/x-www-form-urlencoded");
13             connection.setRequestProperty("Charset""utf-8");
14             DataOutputStream dop = new DataOutputStream(
15                     connection.getOutputStream());
16             dop.writeBytes("token=alexzhou");
17             dop.flush();
18             dop.close();
19  
20             in = new InputStreamReader(connection.getInputStream());
21             BufferedReader bufferedReader = new BufferedReader(in);
22             StringBuffer strBuffer = new StringBuffer();
23             String line = null;
24             while ((line = bufferedReader.readLine()) != null) {
25                 strBuffer.append(line);
26             }
27             result = strBuffer.toString();
28         catch (Exception e) {
29             e.printStackTrace();
30         finally {
31             if (connection != null) {
32                 connection.disconnect();
33             }
34             if (in != null) {
35                 try {
36                     in.close();
37                 catch (IOException e) {
38                     e.printStackTrace();
39                 }
40             }
41  
42         }
43         return result;
44     }

如果参数中有中文的话,可以使用下面的方式进行编码解码:

1 URLEncoder.encode("测试","utf-8")
2 URLDecoder.decode("测试","utf-8");

2.使用Apache的HttpClient访问网络资源
(1)get请求

01 public String executeGet() {
02         String result = null;
03         BufferedReader reader = null;
04         try {
05             HttpClient client = new DefaultHttpClient();
06             HttpGet request = new HttpGet();
07             request.setURI(new URI(
08                     "http://10.0.2.2:8888/data/get/?token=alexzhou"));
09             HttpResponse response = client.execute(request);
10             reader = new BufferedReader(new InputStreamReader(response
11                     .getEntity().getContent()));
12  
13             StringBuffer strBuffer = new StringBuffer("");
14             String line = null;
15             while ((line = reader.readLine()) != null) {
16                 strBuffer.append(line);
17             }
18             result = strBuffer.toString();
19  
20         catch (Exception e) {
21             e.printStackTrace();
22         finally {
23             if (reader != null) {
24                 try {
25                     reader.close();
26                     reader = null;
27                 catch (IOException e) {
28                     e.printStackTrace();
29                 }
30             }
31         }
32  
33         return result;
34     }

(2)post请求

01 public String executePost() {
02         String result = null;
03         BufferedReader reader = null;
04         try {
05             HttpClient client = new DefaultHttpClient();
06             HttpPost request = new HttpPost();
07             request.setURI(new URI("http://10.0.2.2:8888/data/post/"));
08             List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
09             postParameters.add(new BasicNameValuePair("token""alexzhou"));
10             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
11                     postParameters);
12             request.setEntity(formEntity);
13  
14             HttpResponse response = client.execute(request);
15             reader = new BufferedReader(new InputStreamReader(response
16                     .getEntity().getContent()));
17  
18             StringBuffer strBuffer = new StringBuffer("");
19             String line = null;
20             while ((line = reader.readLine()) != null) {
21                 strBuffer.append(line);
22             }
23             result = strBuffer.toString();
24  
25         catch (Exception e) {
26             e.printStackTrace();
27         finally {
28             if (reader != null) {
29                 try {
30                     reader.close();
31                     reader = null;
32                 catch (IOException e) {
33                     e.printStackTrace();
34                 }
35             }
36         }
37  
38         return result;
39     }

3.服务端代码实现
上面是采用两种方式的get和post请求的代码,下面来实现服务端的代码编写,使用python+flask真的非常的简单,就一个文件,前提是你得搭建好python+flask的环境,代码如下:

01 #coding=utf-8
02  
03 import json
04 from flask import Flask,request,render_template
05  
06 app = Flask(__name__)
07  
08 def send_ok_json(data=None):
09     if not data:
10         data = {}
11     ok_json = {'ok':True,'reason':'','data':data}
12     return json.dumps(ok_json)
13  
14 @app.route('/data/get/',methods=['GET'])
15 def data_get():
16     token = request.args.get('token')
17     ret = '%s**%s' %(token,'get')
18     return send_ok_json(ret)
19  
20 @app.route('/data/post/',methods=['POST'])
21 def data_post():
22     token = request.form.get('token')
23     ret = '%s**%s' %(token,'post')
24     return send_ok_json(ret)
25  
26 if __name__ == "__main__":
27     app.run(host="localhost",port=8888,debug=True)

运行服务器,如图:

4. 编写单元测试代码
右击项目:new–》Source Folder取名tests,包名是:com.alexzhou.androidhttp.test(随便取,没有要求),结构如图:

Android Http请求方法汇总_第1张图片
在该包下创建测试类HttpTest,继承自AndroidTestCase。编写这四种方式的测试方法,代码如下:

01 public class HttpTest extends AndroidTestCase {
02  
03     @Override
04     protected void setUp() throws Exception {
05         Log.e("HttpTest""setUp");
06     }
07  
08     @Override
09     protected void tearDown() throws Exception {
10         Log.e("HttpTest""tearDown");
11     }
12  
13     public void testExecuteGet() {
14         Log.e("HttpTest""testExecuteGet");
15         HttpClientTest client = HttpClientTest.getInstance();
16         String result = client.executeGet();
17         Log.e("HttpTest", result);
18     }
19  
20     public void testExecutePost() {
21         Log.e("HttpTest""testExecutePost");
22         HttpClientTest client = HttpClientTest.getInstance();
23         String result = client.executePost();
24         Log.e("HttpTest", result);
25     }
26  
27     public void testExecuteHttpGet() {
28         Log.e("HttpTest""testExecuteHttpGet");
29         HttpClientTest client = HttpClientTest.getInstance();
30         String result = client.executeHttpGet();
31         Log.e("HttpTest", result);
32     }
33  
34     public void testExecuteHttpPost() {
35         Log.e("HttpTest""testExecuteHttpPost");
36         HttpClientTest client = HttpClientTest.getInstance();
37         String result = client.executeHttpPost();
38         Log.e("HttpTest", result);
39     }
40 }

附上HttpClientTest.java的其他代码:

01 public class HttpClientTest {
02  
03     private static final Object mSyncObject = new Object();
04     private static HttpClientTest mInstance;
05  
06     private HttpClientTest() {
07  
08     }
09  
10     public static HttpClientTest getInstance() {
11         synchronized (mSyncObject) {
12             if (mInstance != null) {
13                 return mInstance;
14             }
15             mInstance = new HttpClientTest();
16         }
17         return mInstance;
18     }
19  
20   /**...上面的四个方法...*/
21 }

现在还需要修改Android项目的配置文件AndroidManifest.xml,添加网络访问权限和单元测试的配置,AndroidManifest.xml配置文件的全部代码如下:

01 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
02     package="com.alexzhou.androidhttp"
03     android:versionCode="1"
04     android:versionName="1.0" >
05  
06     <uses-permission android:name="android.permission.INTERNET" />
07  
08     <uses-sdk
09         android:minSdkVersion="8"
10         android:targetSdkVersion="15" />
11  
12     <application
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <uses-library android:name="android.test.runner" />
17  
18         <activity
19             android:name=".MainActivity"
20             android:label="@string/title_activity_main" >
21             <intent-filter>
22                 <action android:name="android.intent.action.MAIN" />
23  
24                 <category android:name="android.intent.category.LAUNCHER" />
25             </intent-filter>
26         </activity>
27     </application>
28  
29     <instrumentation
30         android:name="android.test.InstrumentationTestRunner"
31         android:targetPackage="com.alexzhou.androidhttp" />
32  
33 </manifest>

注意:
android:name=”android.test.InstrumentationTestRunner”这部分不用更改
android:targetPackage=”com.alexzhou.androidhttp”,填写应用程序的包名

5.测试结果
展开测试类HttpTest,依次选中这四个测试方法,右击:Run As–》Android Junit Test。
(1)运行testExecuteHttpGet,结果如图:
(2)运行testExecuteHttpPost,结果如图:
(3)运行testExecuteGet,结果如图:
(4)运行testExecutePost,结果如图:

转载请注明来自:Alex Zhou,本文链接:http://codingnow.cn/android/723.html

你可能感兴趣的:(android)