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() { |
04 |
HttpURLConnection connection = null; |
05 |
InputStreamReader in = null; |
08 |
connection = (HttpURLConnection) url.openConnection(); |
09 |
in = new InputStreamReader(connection.getInputStream()); |
10 |
BufferedReader bufferedReader = new BufferedReader(in); |
11 |
StringBuffer strBuffer = new StringBuffer(); |
13 |
while ((line = bufferedReader.readLine()) != null) { |
14 |
strBuffer.append(line); |
16 |
result = strBuffer.toString(); |
17 |
} catch (Exception e) { |
20 |
if (connection != null) { |
21 |
connection.disconnect(); |
26 |
} catch (IOException e) { |
注意:因为是通过android模拟器访问本地pc服务端,所以不能使用localhost和127.0.0.1,使用127.0.0.1会访问模拟器自身。Android系统为实现通信将PC的IP设置为10.0.2.2
(2)post请求
01 |
public String executeHttpPost() { |
04 |
HttpURLConnection connection = null; |
05 |
InputStreamReader in = null; |
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"); |
20 |
in = new InputStreamReader(connection.getInputStream()); |
21 |
BufferedReader bufferedReader = new BufferedReader(in); |
22 |
StringBuffer strBuffer = new StringBuffer(); |
24 |
while ((line = bufferedReader.readLine()) != null) { |
25 |
strBuffer.append(line); |
27 |
result = strBuffer.toString(); |
28 |
} catch (Exception e) { |
31 |
if (connection != null) { |
32 |
connection.disconnect(); |
37 |
} catch (IOException e) { |
如果参数中有中文的话,可以使用下面的方式进行编码解码:
1 |
URLEncoder.encode("测试","utf-8") |
2 |
URLDecoder.decode("测试","utf-8"); |
2.使用Apache的HttpClient访问网络资源
(1)get请求
01 |
public String executeGet() { |
03 |
BufferedReader reader = null; |
05 |
HttpClient client = new DefaultHttpClient(); |
06 |
HttpGet request = new HttpGet(); |
07 |
request.setURI(new URI( |
09 |
HttpResponse response = client.execute(request); |
10 |
reader = new BufferedReader(new InputStreamReader(response |
11 |
.getEntity().getContent())); |
13 |
StringBuffer strBuffer = new StringBuffer(""); |
15 |
while ((line = reader.readLine()) != null) { |
16 |
strBuffer.append(line); |
18 |
result = strBuffer.toString(); |
20 |
} catch (Exception e) { |
27 |
} catch (IOException e) { |
(2)post请求
01 |
public String executePost() { |
03 |
BufferedReader reader = null; |
05 |
HttpClient client = new DefaultHttpClient(); |
06 |
HttpPost request = new HttpPost(); |
08 |
List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); |
09 |
postParameters.add(new BasicNameValuePair("token", "alexzhou")); |
10 |
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( |
12 |
request.setEntity(formEntity); |
14 |
HttpResponse response = client.execute(request); |
15 |
reader = new BufferedReader(new InputStreamReader(response |
16 |
.getEntity().getContent())); |
18 |
StringBuffer strBuffer = new StringBuffer(""); |
20 |
while ((line = reader.readLine()) != null) { |
21 |
strBuffer.append(line); |
23 |
result = strBuffer.toString(); |
25 |
} catch (Exception e) { |
32 |
} catch (IOException e) { |
3.服务端代码实现
上面是采用两种方式的get和post请求的代码,下面来实现服务端的代码编写,使用python+flask真的非常的简单,就一个文件,前提是你得搭建好python+flask的环境,代码如下:
04 |
from flask import Flask,request,render_template |
08 |
def send_ok_json(data=None): |
11 |
ok_json = {'ok':True,'reason':'','data':data} |
12 |
return json.dumps(ok_json) |
14 |
@app.route('/data/get/',methods=['GET']) |
16 |
token = request.args.get('token') |
17 |
ret = '%s**%s' %(token,'get') |
18 |
return send_ok_json(ret) |
20 |
@app.route('/data/post/',methods=['POST']) |
22 |
token = request.form.get('token') |
23 |
ret = '%s**%s' %(token,'post') |
24 |
return send_ok_json(ret) |
26 |
if __name__ == "__main__": |
27 |
app.run(host="localhost",port=8888,debug=True) |
运行服务器,如图:

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

在该包下创建测试类HttpTest,继承自AndroidTestCase。编写这四种方式的测试方法,代码如下:
01 |
public class HttpTest extends AndroidTestCase { |
04 |
protected void setUp() throws Exception { |
05 |
Log.e("HttpTest", "setUp"); |
09 |
protected void tearDown() throws Exception { |
10 |
Log.e("HttpTest", "tearDown"); |
13 |
public void testExecuteGet() { |
14 |
Log.e("HttpTest", "testExecuteGet"); |
15 |
HttpClientTest client = HttpClientTest.getInstance(); |
16 |
String result = client.executeGet(); |
17 |
Log.e("HttpTest", result); |
20 |
public void testExecutePost() { |
21 |
Log.e("HttpTest", "testExecutePost"); |
22 |
HttpClientTest client = HttpClientTest.getInstance(); |
23 |
String result = client.executePost(); |
24 |
Log.e("HttpTest", result); |
27 |
public void testExecuteHttpGet() { |
28 |
Log.e("HttpTest", "testExecuteHttpGet"); |
29 |
HttpClientTest client = HttpClientTest.getInstance(); |
30 |
String result = client.executeHttpGet(); |
31 |
Log.e("HttpTest", result); |
34 |
public void testExecuteHttpPost() { |
35 |
Log.e("HttpTest", "testExecuteHttpPost"); |
36 |
HttpClientTest client = HttpClientTest.getInstance(); |
37 |
String result = client.executeHttpPost(); |
38 |
Log.e("HttpTest", result); |
附上HttpClientTest.java的其他代码:
01 |
public class HttpClientTest { |
03 |
private static final Object mSyncObject = new Object(); |
04 |
private static HttpClientTest mInstance; |
06 |
private HttpClientTest() { |
10 |
public static HttpClientTest getInstance() { |
11 |
synchronized (mSyncObject) { |
12 |
if (mInstance != null) { |
15 |
mInstance = new HttpClientTest(); |
现在还需要修改Android项目的配置文件AndroidManifest.xml,添加网络访问权限和单元测试的配置,AndroidManifest.xml配置文件的全部代码如下:
02 |
package="com.alexzhou.androidhttp" |
03 |
android:versionCode="1" |
04 |
android:versionName="1.0" > |
06 |
<uses-permission android:name="android.permission.INTERNET" /> |
09 |
android:minSdkVersion="8" |
10 |
android:targetSdkVersion="15" /> |
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" /> |
19 |
android:name=".MainActivity" |
20 |
android:label="@string/title_activity_main" > |
22 |
<action android:name="android.intent.action.MAIN" /> |
24 |
<category android:name="android.intent.category.LAUNCHER" /> |
30 |
android:name="android.test.InstrumentationTestRunner" |
31 |
android:targetPackage="com.alexzhou.androidhttp" /> |
注意:
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