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

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

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

(1)get请求

01 publicString executeHttpGet() {
02 String result =null;
03 URL url =null;
04 HttpURLConnection connection =null;
05 InputStreamReader in =null;
06 try{
07 url =newURL("http://10.0.2.2:8888/data/get/?token=alexzhou");
08 connection = (HttpURLConnection) url.openConnection();
09 in =newInputStreamReader(connection.getInputStream());
10 BufferedReader bufferedReader =newBufferedReader(in);
11 StringBuffer strBuffer =newStringBuffer();
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 returnresult;
33 }

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

(2)post请求

01 publicString executeHttpPost() {
02 String result =null;
03 URL url =null;
04 HttpURLConnection connection =null;
05 InputStreamReader in =null;
06 try{
07 url =newURL("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 =newDataOutputStream(
15 connection.getOutputStream());
16 dop.writeBytes("token=alexzhou");
17 dop.flush();
18 dop.close();
19
20 in =newInputStreamReader(connection.getInputStream());
21 BufferedReader bufferedReader =newBufferedReader(in);
22 StringBuffer strBuffer =newStringBuffer();
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 returnresult;
44 }

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

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

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

01 publicString executeGet() {
02 String result =null;
03 BufferedReader reader =null;
04 try{
05 HttpClient client =newDefaultHttpClient();
06 HttpGet request =newHttpGet();
07 request.setURI(newURI(
08 "http://10.0.2.2:8888/data/get/?token=alexzhou"));
09 HttpResponse response = client.execute(request);
10 reader =newBufferedReader(newInputStreamReader(response
11 .getEntity().getContent()));
12
13 StringBuffer strBuffer =newStringBuffer("");
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 returnresult;
34 }

(2)post请求

01 publicString executePost() {
02 String result =null;
03 BufferedReader reader =null;
04 try{
05 HttpClient client =newDefaultHttpClient();
06 HttpPost request =newHttpPost();
07 request.setURI(newURI("http://10.0.2.2:8888/data/post/"));
08 List<NameValuePair> postParameters =newArrayList<NameValuePair>();
09 postParameters.add(newBasicNameValuePair("token","alexzhou"));
10 UrlEncodedFormEntity formEntity =newUrlEncodedFormEntity(
11 postParameters);
12 request.setEntity(formEntity);
13
14 HttpResponse response = client.execute(request);
15 reader =newBufferedReader(newInputStreamReader(response
16 .getEntity().getContent()));
17
18 StringBuffer strBuffer =newStringBuffer("");
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 returnresult;
39 }

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

01 #coding=utf-8
02
03 importjson
04 fromflaskimportFlask,request,render_template
05
06 app=Flask(__name__)
07
08 defsend_ok_json(data=None):
09 ifnotdata:
10 data={}
11 ok_json={'ok':True,'reason':'','data':data}
12 returnjson.dumps(ok_json)
13
14 @app.route('/data/get/',methods=['GET'])
15 defdata_get():
16 token=request.args.get('token')
17 ret='%s**%s'%(token,'get')
18 returnsend_ok_json(ret)
19
20 @app.route('/data/post/',methods=['POST'])
21 defdata_post():
22 token=request.form.get('token')
23 ret='%s**%s'%(token,'post')
24 returnsend_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 publicclassHttpTestextendsAndroidTestCase {
02
03 @Override
04 protectedvoidsetUp()throwsException {
05 Log.e("HttpTest","setUp");
06 }
07
08 @Override
09 protectedvoidtearDown()throwsException {
10 Log.e("HttpTest","tearDown");
11 }
12
13 publicvoidtestExecuteGet() {
14 Log.e("HttpTest","testExecuteGet");
15 HttpClientTest client = HttpClientTest.getInstance();
16 String result = client.executeGet();
17 Log.e("HttpTest", result);
18 }
19
20 publicvoidtestExecutePost() {
21 Log.e("HttpTest","testExecutePost");
22 HttpClientTest client = HttpClientTest.getInstance();
23 String result = client.executePost();
24 Log.e("HttpTest", result);
25 }
26
27 publicvoidtestExecuteHttpGet() {
28 Log.e("HttpTest","testExecuteHttpGet");
29 HttpClientTest client = HttpClientTest.getInstance();
30 String result = client.executeHttpGet();
31 Log.e("HttpTest", result);
32 }
33
34 publicvoidtestExecuteHttpPost() {
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 publicclassHttpClientTest {
02
03 privatestaticfinalObject mSyncObject =newObject();
04 privatestaticHttpClientTest mInstance;
05
06 privateHttpClientTest() {
07
08 }
09
10 publicstaticHttpClientTest getInstance() {
11 synchronized(mSyncObject) {
12 if(mInstance !=null) {
13 returnmInstance;
14 }
15 mInstance =newHttpClientTest();
16 }
17 returnmInstance;
18 }
19
20 /**...上面的四个方法...*/
21 }

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

01 <manifestxmlns: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-permissionandroid: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-libraryandroid:name="android.test.runner"/>
17
18 <activity
19 android:name=".MainActivity"
20 android:label="@string/title_activity_main">
21 <intent-filter>
22 <actionandroid:name="android.intent.action.MAIN"/>
23
24 <categoryandroid: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

更多相关文章

  1. android手机通讯录备份还原代码
  2. 详解Android获取系统内核版本的方法与实现代码
  3. Android 中的单元测试(使用AndroidTestCase 进行 Content Provid
  4. Android CTS 测试研究之二
  5. android典型代码系列(二十八)------通话记录的操作
  6. 【Android】Android清除本地数据缓存代码
  7. CyanogenMod开源代码
  8. 基于TCP/IP协议的Java服务端与Android客户端的Socket通信

随机推荐

  1. Android中用layer-list编写阴影效果
  2. Android Drawable Resources系列8:
  3. Android发送短信时 短信内容超长处理
  4. 1.5 Button
  5. Android service后台执行定时任务
  6. android 图片解码显示流程
  7. 获取 Android 4.2 的 ROOT 权限(越狱)
  8. Android Kotlin ListView的使用
  9. Android(安卓)调用系统Camera 程序照相,获
  10. android usb Host模式下与usb Hid 设备的