位置: 编程技术 - 正文

Android Http请求方法汇总

编辑:rootadmin

推荐整理分享Android Http请求方法汇总,希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!

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

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

(1)get请求

?publicString executeHttpGet() { String result = null; URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; try{ url = newURL(" connection = (HttpURLConnection) url.openConnection(); in = newInputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = newBufferedReader(in); StringBuffer strBuffer = newStringBuffer(); 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(); } } } returnresult; }

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

(2)post请求

?publicString executeHttpPost() { String result = null; URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; try{ url = newURL(" 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 = newDataOutputStream( connection.getOutputStream()); dop.writeBytes("token=alexzhou"); dop.flush(); dop.close(); in = newInputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = newBufferedReader(in); StringBuffer strBuffer = newStringBuffer(); 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(); } } } returnresult; }

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

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

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

?publicString executeGet() { String result = null; BufferedReader reader = null; try{ HttpClient client = newDefaultHttpClient(); HttpGet request = newHttpGet(); request.setURI(newURI( " HttpResponse response = client.execute(request); reader = newBufferedReader(newInputStreamReader(response .getEntity().getContent())); StringBuffer strBuffer = newStringBuffer(""); 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(); } } } returnresult; }

(2)post请求

?publicString executePost() { String result = null; BufferedReader reader = null; try{ HttpClient client = newDefaultHttpClient(); HttpPost request = newHttpPost(); request.setURI(newURI(" List<NameValuePair> postParameters = newArrayList<NameValuePair>(); postParameters.add(newBasicNameValuePair("token", "alexzhou")); UrlEncodedFormEntity formEntity = newUrlEncodedFormEntity( postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request); reader = newBufferedReader(newInputStreamReader(response .getEntity().getContent())); StringBuffer strBuffer = newStringBuffer(""); 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(); } } } returnresult; }Android Http请求方法汇总

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

?#coding=utf-8 importjsonfromflask importFlask,request,render_template app =Flask(__name__) defsend_ok_json(data=None): ifnot data: data ={} ok_json ={'ok':True,'reason':'','data':data} returnjson.dumps(ok_json) @app.route('/data/get/',methods=['GET'])defdata_get(): token =request.args.get('token') ret ='%s**%s' %(token,'get') returnsend_ok_json(ret) @app.route('/data/post/',methods=['POST'])defdata_post(): token =request.form.get('token') ret ='%s**%s' %(token,'post') returnsend_ok_json(ret) if__name__ =="__main__": app.run(host="localhost",port=,debug=True)

运行服务器,如图:

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

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

?publicclass HttpTest extendsAndroidTestCase { @Override protectedvoid setUp() throwsException { Log.e("HttpTest", "setUp"); } @Override protectedvoid tearDown() throwsException { Log.e("HttpTest", "tearDown"); } publicvoid testExecuteGet() { Log.e("HttpTest", "testExecuteGet"); HttpClientTest client = HttpClientTest.getInstance(); String result = client.executeGet(); Log.e("HttpTest", result); } publicvoid testExecutePost() { Log.e("HttpTest", "testExecutePost"); HttpClientTest client = HttpClientTest.getInstance(); String result = client.executePost(); Log.e("HttpTest", result); } publicvoid testExecuteHttpGet() { Log.e("HttpTest", "testExecuteHttpGet"); HttpClientTest client = HttpClientTest.getInstance(); String result = client.executeHttpGet(); Log.e("HttpTest", result); } publicvoid testExecuteHttpPost() { Log.e("HttpTest", "testExecuteHttpPost"); HttpClientTest client = HttpClientTest.getInstance(); String result = client.executeHttpPost(); Log.e("HttpTest", result); }}

附上HttpClientTest.java的其他代码:

?publicclass HttpClientTest { privatestatic final Object mSyncObject = newObject(); privatestatic HttpClientTest mInstance; privateHttpClientTest() { } publicstatic HttpClientTest getInstance() { synchronized(mSyncObject) { if(mInstance != null) { returnmInstance; } mInstance = newHttpClientTest(); } returnmInstance; } /**...上面的四个方法...*/}

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

?<manifestxmlns:android=" package="com.alexzhou.androidhttp" android:versionCode="1" android:versionName="1.0"> <uses-permissionandroid:name="android.permission.INTERNET"/> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion=""/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <uses-libraryandroid:name="android.test.runner"/> <activity android:name=".MainActivity" android:label="@string/title_activity_main"> <intent-filter> <actionandroid:name="android.intent.action.MAIN"/> <categoryandroid: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,结果如图:

转载请注明来自:Alex Zhou,本文链接:

使用php作为桥梁让android客户端和mysql数据库进行通信 首先,我发现我越来越喜欢写程序了,这是一种很好的状态,加油!我的开发环境:MacPROXAMPP安装之后有了mysql和apache,启动mysql和apache,如果无法启动ap

Material Design控件使用(四) 本文要实现内容移动时,标题栏自动缩小/放大的效果,效果如下:控件介绍这次需要用到得新控件比较多,主要有以下几个:*CoordinatorLayout组织它的子v

获取控件的宽和高 一:自定义MyImageView继承ImageView/***这个类纯粹是为了看到控件的onMeasure方法和onDraw方法的执行情况*任何控件都是同一个道理*@authorAdministrator**/publicclassMy

标签: Android Http请求方法汇总

本文链接地址:https://www.jiuchutong.com/biancheng/378039.html 转载请保留说明!

上一篇:解决首次安装android sdk platform-tools文件夹下adb命令无法运行(首次安装操作系统称为什么盘)

下一篇:Material Design控件使用(四)(.material design)

  • 什么是转登记纳税人
  • 对方给我开的增值税专票丢失
  • 取得的免税发票怎么开
  • 科普一下发票知识
  • 内含报酬率与必要报酬率相等
  • 企业所得税计提分录
  • 火车票增值税申报表怎么填
  • 出口专用发票应在哪里开
  • 房地产开发企业土地增值税清算
  • 材料成本差异结转借贷方向
  • 银行承兑汇票怎么取钱
  • 收到政府土地收回的短信
  • 应交增值税明细科目核算内容
  • 公司借款给个人超过一年未还
  • 工程未完工但已开票
  • 房屋租赁合同税率怎么算
  • 购买存货的进口商品
  • 估价入账固定资产实际入账时补提折旧吗?
  • 营改增后发票上必须要开具税收分类编码吗?
  • 年薪制离职补偿金
  • 停车费专用发票可以抵扣进项税吗
  • 一般纳税人技术开发税率
  • 装修待摊费用当月摊销吗
  • 投资收益填在经营所得申报表的哪里
  • 企业研发活动中心职责
  • 公会经费开支范围
  • 企业债卷利息收入是营业收入吗
  • 土地使用权评估中的成本法
  • 签订租赁合同的期限
  • 电脑bios找不到vt
  • 汇算清缴时业务招待费税收金额为零是什么原因
  • 贴吧热门评论
  • 公司已开票给客户,但客户未打款怎么办?
  • 工业企业应付账款周转率多少合适
  • 注册造价师挂靠费如何缴个税?
  • 柬埔寨 吴哥窟
  • php实现计算百度百科
  • php事务特性
  • php提交表单数据有哪几种方法
  • python机器人编程控制
  • js怎样遍历对象中的每个元素
  • PHP 实现等比压缩图片尺寸和大小实例代码
  • 贷款利息现金流量项目
  • 残疾人保证金如何做账
  • 交去年企业所得税怎么做资产负债表
  • c语言中局部变量和全局变量同名
  • 织梦安装详细教程
  • java sc
  • mongodb 统计
  • linux中mongodb启动
  • 货款分批付的会计分录
  • 什么是销项税额转出
  • 内账会计有法律风险吗
  • 存货跌价准备在年报哪里
  • 内部审计和外部审计可以相互接触对方的
  • 劳务外经证预缴税款
  • 结转后还可以改凭证吗
  • 一般纳税人销售旧货可以开专票吗
  • 2010年漏记的费用,11年该如何记账?
  • 房地产公司开发的商品房应作为固定资产核算
  • linux快速清空大日志文件
  • Windows时间同步时出错该怎么解决?
  • xp系统怎样设置无线网络连接
  • win11玩dota2
  • linux 常用 命令
  • 关机你的电脑遇到问题,需要重新启动,我们只收集
  • win8怎么系统重装系统
  • 网络连接受限怎么处理win8
  • win10预览版21h2
  • shell脚本实现自动部署
  • activity怎么用
  • javascript定律
  • jquery怎么遍历
  • jquery版本区别
  • javascript简单代码
  • jQuery Easyui datagrid/treegrid 清空数据
  • 瑞士州税
  • 怎样打印护士资格证
  • 财务审计报告哪个位置可以看出是否亏损
  • 成都国税网上办税服务厅
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设