Android Http请求方法汇总

来源:互联网 发布:c语言中实型常量 编辑:程序博客网 时间:2024/06/10 01:14

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

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

(1)get请求

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

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

(2)post请求

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

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

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

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

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

(2)post请求

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

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

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

运行服务器,如图:

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


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

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

附上HttpClientTest.java的其他代码:

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

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

 
01<manifestxmlns:android="http://schemas.android.com/apk/res/android"
02package="com.alexzhou.androidhttp"
03android:versionCode="1"
04android:versionName="1.0">
05
06<uses-permissionandroid:name="android.permission.INTERNET"/>
07
08<uses-sdk
09android:minSdkVersion="8"
10android:targetSdkVersion="15"/>
11
12<application
13android:icon="@drawable/ic_launcher"
14android:label="@string/app_name"
15android:theme="@style/AppTheme">
16<uses-libraryandroid:name="android.test.runner"/>
17
18<activity
19android:name=".MainActivity"
20android: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
30android:name="android.test.InstrumentationTestRunner"
31android: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,结果如图:

原创粉丝点击