Android Http请求方法汇总
2014-11-10 22:50
183 查看
这篇文章主要实现了在Android中使用JDK的HttpURLConnection和Apache的HttpClient访问网络资源,服务端采用python+flask编写,使用Servlet太麻烦了。关于Http协议的相关知识,可以在网上查看相关资料。代码比较简单,就不详细解释了。
1. 使用JDK中HttpURLConnection访问网络资源
(1)get请求
?
注意:因为是通过android模拟器访问本地pc服务端,所以不能使用localhost和127.0.0.1,使用127.0.0.1会访问模拟器自身。Android系统为实现通信将PC的IP设置为10.0.2.2
(2)post请求
?
如果参数中有中文的话,可以使用下面的方式进行编码解码:
?
2.使用Apache的HttpClient访问网络资源
(1)get请求
?
(2)post请求
?
3.服务端代码实现
上面是采用两种方式的get和post请求的代码,下面来实现服务端的代码编写,使用python+flask真的非常的简单,就一个文件,前提是你得搭建好python+flask的环境,代码如下:
?
运行服务器,如图:
4. 编写单元测试代码
右击项目:new–》Source Folder取名tests,包名是:com.alexzhou.androidhttp.test(随便取,没有要求),结构如图:
在该包下创建测试类HttpTest,继承自AndroidTestCase。编写这四种方式的测试方法,代码如下:
?
附上HttpClientTest.java的其他代码:
?
现在还需要修改Android项目的配置文件AndroidManifest.xml,添加网络访问权限和单元测试的配置,AndroidManifest.xml配置文件的全部代码如下:
?
注意:
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,结果如图:
1. 使用JDK中HttpURLConnection访问网络资源
(1)get请求
?
(2)post请求
?
?
(1)get请求
?
?
上面是采用两种方式的get和post请求的代码,下面来实现服务端的代码编写,使用python+flask真的非常的简单,就一个文件,前提是你得搭建好python+flask的环境,代码如下:
?
4. 编写单元测试代码
右击项目:new–》Source Folder取名tests,包名是:com.alexzhou.androidhttp.test(随便取,没有要求),结构如图:
在该包下创建测试类HttpTest,继承自AndroidTestCase。编写这四种方式的测试方法,代码如下:
?
?
?
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请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总
- Android Http请求方法汇总