Android Http请求方法汇总

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

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

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;}

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

1 URLEncoder.encode("测试","utf-8")
2 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-8import json
from flask import Flask,request,render_templateapp = 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 {@Overrideprotected void setUp() throws Exception {Log.e("HttpTest", "setUp");}@Overrideprotected 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-sdkandroid:minSdkVersion="8"android:targetSdkVersion="15" /><applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><uses-library android:name="android.test.runner" /><activityandroid: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><instrumentationandroid: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,结果如图:

转载请注明来自:Alex Zhou,本文链接:http://codingnow.cn/android/723.html

Android Http请求方法汇总相关推荐

  1. android网络请求框架汇总

    网络 使用网络库不要忘记添加网络权限 2.1网络_Volley · 简介: Volley的中文翻译为"齐射.并发",是在2013年的Google大会上发布的一款Android平台网 ...

  2. 常见的Android数据传递方法汇总

    一.Intent与Bundle 1.Activty与Activity 1.1.传递简单数据 (1) 传单个值(以String类型为例) 发送数据 Intent intent = new Intent( ...

  3. android倒计时实现方法,Android实现倒计时方法汇总

    Android开发中经常会有倒计时的功能,下面将总结出常见的集中实现方式. 1.直接使用Handler的消息机制来实现 xml布局中文件如下: android:layout_width="m ...

  4. android 本地文件读写,Android 读写文件方法汇总

    一. 从resource中的raw文件夹中获取文件并读取数据(资源文件只能读不能写) String res = ""; try{ InputStream in = getResou ...

  5. Android地图权限处理,Android 使用地图时的权限请求方法

    在初始化自己位置的时候请求定位权限: Constants.ACCESS_FINE_LOCATION_COMMANDS_REQUEST_CODE是自定义的常量值==0x01 if (ContextCom ...

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

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

  7. [Android]Android布局文件中的android:id=@*属性使用方法汇总以及介绍

    由于项目需要进行Android开发,因此一边开发,一边查阅资料,一边总结了Android布局文件中android:id="@*"属性的使用方法汇总以及介绍.id资源的引用 andr ...

  8. android 手机 平板同屏,酷乐视Q6投影仪Android手机/平板同屏方法汇总

    酷乐视Q6投影仪Android手机/平板同屏方法汇总,详情如下: Q:华为手机如何同屏? 1)手机与投影机同时打开WiFi开关(是否连接网络均可): 2)投影机点击主界面无线同屏图标 3)手机端操作如 ...

  9. android手机性能优化,安卓手机性能怎么优化 安卓手机性能方法汇总

    虽然说安卓手机的性能与它本身的配置有很大的关联,但是有一部分与手机的设置有很多大关系.下面,就一起来看看安卓手机性能优化方法汇总吧. ★Build.prop (编辑/system/build.prop ...

最新文章

  1. 15 个 JavaScript Web UI 库
  2. 「SAP技术」交货单发货过账报错 - Material's product unit must be entered in whole numbers - 之对策
  3. KNN算法与Kd树(转载+代码详细解释)
  4. view.post不执行的坑点
  5. 数据结构(二)——堆
  6. (转)Arcgis for JS之Cluster聚类分析的实现
  7. 使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)——第1部分
  8. 开始学习python标准库---os
  9. 人生理解---2、看《程序员年龄增大后的职业出路是什么》有感
  10. centos7中 npm install express 时Error: Cannot find module 'express'错误
  11. 【正点原子MP157连载】第六章STM32Cube固件包-摘自【正点原子】STM32MP1 M4裸机CubeIDE开发指南
  12. cfturbo破解版-叶轮设计软件
  13. Web前端第三季(JavaScript):十二:第4章: 表单校验案例:401-开发注册表单页面+402-表单提交事件和获取html元素+403-完成用户名和邮箱的校验
  14. PostgreSQL shapefile 导入导出
  15. Mac火爆游戏---英雄联盟LOL
  16. PADS Logic原理图设计
  17. Excel技巧之插入图表
  18. IOS开发—iOS视频拍摄与压缩
  19. 登录失败:用户帐户限制。可能的原因包括不允许空密码登录时间限制或强制的策略限制。
  20. John McCarthy:人工智能之父

热门文章

  1. Matlab可视化四维数据
  2. 临近毕业,图像类SCI源刊哪本审稿快?
  3. 一个疯子的DK马历程(易中天说:悲剧啊)
  4. python终端命令执行提示找不到自定义模块
  5. 2019美团后台开发工程师笔试
  6. obj文件和mtl文件格式说明
  7. linux里的chdir()
  8. 如何将图片批量压缩?全面盘点这几种小方法
  9. 关于印发《留学回国人员申办上海常住户口实施细则》的通知
  10. python小工具------将H264/H265码流文件转为一帧一帧的JPEG文件