[转]  原文

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

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

(1)get请求

public String executeHttpGet() { 		String result = null; 		URL url = null; 		HttpURLConnection connection = null; 		InputStreamReader in = null; 		try { 			url = new URL("http://10.0.2.2:8888/data/get/?token=alexzhou"); 			connection = (HttpURLConnection) url.openConnection(); 			in = new InputStreamReader(connection.getInputStream()); 			BufferedReader bufferedReader = new BufferedReader(in); 			StringBuffer strBuffer = new StringBuffer(); 			String line = null; 			while ((line = bufferedReader.readLine()) != null) { 				strBuffer.append(line); 			} 			result = strBuffer.toString(); 		} catch (Exception e) { 			e.printStackTrace(); 		} finally { 			if (connection != null) { 				connection.disconnect(); 			} 			if (in != null) { 				try { 					in.close(); 				} catch (IOException e) { 					e.printStackTrace(); 				} 			}  		} 		return result; 	}

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

(2)post请求

public String executeHttpPost() { 		String result = null; 		URL url = null; 		HttpURLConnection connection = null; 		InputStreamReader in = null; 		try { 			url = new URL("http://10.0.2.2:8888/data/post/"); 			connection = (HttpURLConnection) url.openConnection(); 			connection.setDoInput(true); 			connection.setDoOutput(true); 			connection.setRequestMethod("POST"); 			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 			connection.setRequestProperty("Charset", "utf-8"); 			DataOutputStream dop = new DataOutputStream( 					connection.getOutputStream()); 			dop.writeBytes("token=alexzhou"); 			dop.flush(); 			dop.close();  			in = new InputStreamReader(connection.getInputStream()); 			BufferedReader bufferedReader = new BufferedReader(in); 			StringBuffer strBuffer = new StringBuffer(); 			String line = null; 			while ((line = bufferedReader.readLine()) != null) { 				strBuffer.append(line); 			} 			result = strBuffer.toString(); 		} catch (Exception e) { 			e.printStackTrace(); 		} finally { 			if (connection != null) { 				connection.disconnect(); 			} 			if (in != null) { 				try { 					in.close(); 				} catch (IOException e) { 					e.printStackTrace(); 				} 			}  		} 		return result; 	}

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

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

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

public String executeGet() { 		String result = null; 		BufferedReader reader = null; 		try { 			HttpClient client = new DefaultHttpClient(); 			HttpGet request = new HttpGet(); 			request.setURI(new URI( 					"http://10.0.2.2:8888/data/get/?token=alexzhou")); 			HttpResponse response = client.execute(request); 			reader = new BufferedReader(new InputStreamReader(response 					.getEntity().getContent()));  			StringBuffer strBuffer = new StringBuffer(""); 			String line = null; 			while ((line = reader.readLine()) != null) { 				strBuffer.append(line); 			} 			result = strBuffer.toString();  		} catch (Exception e) { 			e.printStackTrace(); 		} finally { 			if (reader != null) { 				try { 					reader.close(); 					reader = null; 				} catch (IOException e) { 					e.printStackTrace(); 				} 			} 		}  		return result; 	}

(2)post请求

public String executePost() { 		String result = null; 		BufferedReader reader = null; 		try { 			HttpClient client = new DefaultHttpClient(); 			HttpPost request = new HttpPost(); 			request.setURI(new URI("http://10.0.2.2:8888/data/post/")); 			List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 			postParameters.add(new BasicNameValuePair("token", "alexzhou")); 			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( 					postParameters); 			request.setEntity(formEntity);  			HttpResponse response = client.execute(request); 			reader = new BufferedReader(new InputStreamReader(response 					.getEntity().getContent()));  			StringBuffer strBuffer = new StringBuffer(""); 			String line = null; 			while ((line = reader.readLine()) != null) { 				strBuffer.append(line); 			} 			result = strBuffer.toString();  		} catch (Exception e) { 			e.printStackTrace(); 		} finally { 			if (reader != null) { 				try { 					reader.close(); 					reader = null; 				} catch (IOException e) { 					e.printStackTrace(); 				} 			} 		}  		return result; 	}

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

#coding=utf-8  import json from flask import Flask,request,render_template  app = Flask(__name__)  def send_ok_json(data=None):     if not data:         data = {}     ok_json = {'ok':True,'reason':'','data':data}     return json.dumps(ok_json)  @app.route('/data/get/',methods=['GET']) def data_get():     token = request.args.get('token')     ret = '%s**%s' %(token,'get')     return send_ok_json(ret)  @app.route('/data/post/',methods=['POST']) def data_post():     token = request.form.get('token')     ret = '%s**%s' %(token,'post')     return send_ok_json(ret)  if __name__ == "__main__":     app.run(host="localhost",port=8888,debug=True)

运行服务器,如图:

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


在该包下创建测试类HttpTest,继承自AndroidTestCase。编写这四种方式的测试方法,代码如下:

public class HttpTest extends AndroidTestCase {  	@Override 	protected void setUp() throws Exception { 		Log.e("HttpTest", "setUp"); 	}  	@Override 	protected void tearDown() throws Exception { 		Log.e("HttpTest", "tearDown"); 	}  	public void testExecuteGet() { 		Log.e("HttpTest", "testExecuteGet"); 		HttpClientTest client = HttpClientTest.getInstance(); 		String result = client.executeGet(); 		Log.e("HttpTest", result); 	}  	public void testExecutePost() { 		Log.e("HttpTest", "testExecutePost"); 		HttpClientTest client = HttpClientTest.getInstance(); 		String result = client.executePost(); 		Log.e("HttpTest", result); 	}  	public void testExecuteHttpGet() { 		Log.e("HttpTest", "testExecuteHttpGet"); 		HttpClientTest client = HttpClientTest.getInstance(); 		String result = client.executeHttpGet(); 		Log.e("HttpTest", result); 	}  	public void testExecuteHttpPost() { 		Log.e("HttpTest", "testExecuteHttpPost"); 		HttpClientTest client = HttpClientTest.getInstance(); 		String result = client.executeHttpPost(); 		Log.e("HttpTest", result); 	} }

附上HttpClientTest.java的其他代码:

public class HttpClientTest {  	private static final Object mSyncObject = new Object(); 	private static HttpClientTest mInstance;  	private HttpClientTest() {  	}  	public static HttpClientTest getInstance() { 		synchronized (mSyncObject) { 			if (mInstance != null) { 				return mInstance; 			} 			mInstance = new HttpClientTest(); 		} 		return mInstance; 	}    /**...上面的四个方法...*/ }

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.alexzhou.androidhttp"     android:versionCode="1"     android:versionName="1.0" >      <uses-permission android:name="android.permission.INTERNET" />      <uses-sdk         android:minSdkVersion="8"         android:targetSdkVersion="15" />      <application         android:icon="@drawable/ic_launcher"         android:label="@string/app_name"         android:theme="@style/AppTheme" >         <uses-library android:name="android.test.runner" />          <activity             android:name=".MainActivity"             android:label="@string/title_activity_main" >             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application>      <instrumentation         android:name="android.test.InstrumentationTestRunner"         android:targetPackage="com.alexzhou.androidhttp" />  </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,结果如图:

Android Http请求方法汇总的更多相关文章

  1. jQuery ajax中的get请求方法汇总

    $.get() Defination and Usage 从服务端以HTTP GET方式获取数据 Examples 请求test.php,但是忽略返回的数据 $.get("test.php& ...

  2. android网络请求库volley方法详解

    使用volley进行网络请求:需先将volley包导入androidstudio中 File下的Project Structrue,点加号导包 volley网络请求步骤: 1. 创建请求队列     ...

  3. Android学习之六种事件响应方法汇总

    java源码如下: 1.MainActivity.java源码 package com.example.responsetest; import android.app.Activity; impor ...

  4. GitHub上史上最全的Android开源项目分类汇总 (转)

    GitHub上史上最全的Android开源项目分类汇总 标签: github android 开源 | 发表时间:2014-11-23 23:00 | 作者:u013149325 分享到: 出处:ht ...

  5. GitHub上史上最全的Android开源项目分类汇总

    今天在看博客的时候,无意中发现了 @Trinea 在GitHub上的一个项目 Android开源项目分类汇总 ,由于类容太多了,我没有一个个完整地看完,但是里面介绍的开源项目都非常有参考价值,包括很炫 ...

  6. Android 开源项目分类汇总(转)

    Android 开源项目分类汇总(转) ## 第一部分 个性化控件(View)主要介绍那些不错个性化的 View,包括 ListView.ActionBar.Menu.ViewPager.Galler ...

  7. ANDROID内存优化——大汇总(转)

    原文作者博客:转载请注明本文出自大苞米的博客(http://blog.csdn.net/a396901990),谢谢支持! ANDROID内存优化(大汇总——上) 写在最前: 本文的思路主要借鉴了20 ...

  8. Android 开源项目分类汇总

    Android 开源项目分类汇总 Android 开源项目第一篇——个性化控件(View)篇  包括ListView.ActionBar.Menu.ViewPager.Gallery.GridView ...

  9. Android开源项目分类汇总【畜生级别】[转]

    Android开源项目分类汇总 欢迎大家推荐好的Android开源项目,可直接Commit或在 收集&提交页 中告诉我,欢迎Star.Fork :) 微博:Trinea    主页:www.t ...

随机推荐

  1. Flume interceptor 使用注意事项

    1. 在使用 Regex Filtering Interceptor的时候一个属性是excludeEvents 当它的值为true 的时候,过滤掉匹配到当前正则表达式的一行 当它的值为false的时候 ...

  2. BZOJ1001 [BeiJing2006]狼抓兔子(平面图最小割转最短路)

    ..和HDU3870类似..注意n=1和m=1的情况. #include<cstdio> #include<cstring> #include<queue> #in ...

  3. 关于listView 中的聚焦问题

    我在使用listView+adapter 中,遇到一个问题,就是item项添加了若干个可以被监听的控件后 在listView中的setOnItemClickListener失效了 原因是焦点已经在it ...

  4. Repeater 双向排序

      做项目的时候,DataGrid ,DataList,Repeater 三个控件都是很优秀的数据显示控件,DataGrid的方便,简单易用,功能强大,但对性能会有所影响,在loading页面的时候大 ...

  5. Python: 常用list, string处理功能

    #1. keep strings in double quote as one word when split string to words #e.g. str = ‘a b "is si ...

  6. 编写unit test以及自动化测试WebDriver

    http://msdn.microsoft.com/en-us/library/hh694602.aspx#BKMK_Quick_starts   http://www.seleniumhq.org/ ...

  7. 利用ngxtop实时监控nginx的访问情况

    关于对nginx web server的实时访问的实时监控问题,我很久之前就想实现的,现在虽有nginx自带的status扩展,但那是全局的,无法细分到vhost,并且提供的metric也很少,加之目 ...

  8. Nginx 利用 X-Accel-Redirect response.setHeader 控制文件下载

    nginx.conf location / { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP ...

  9. Codeforces Round #253 (Div. 2) B - Kolya and Tandem Repeat

    本题要考虑字符串本身就存在tandem, 如测试用例 aaaaaaaaabbb 3 输出结果应该是8而不是6,因为字符串本身的tanderm时最长的 故要考虑字符串本身的最大的tanderm和添加k个 ...

  10. ACM 分数加减法

    分数加减法 时间限制:3000 ms  |  内存限制:65535 KB 难度:2   描述 编写一个C程序,实现两个分数的加减法   输入 输入包含多行数据 每行数据是一个字符串,格式是" ...