欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android请求java端通用类

程序员文章站 2022-08-31 13:38:23
android请求java端通用类 httpclient的使用步骤 3.1 创建httpclient对象 httpclient httpclient = new defaul...
android请求java端通用类

httpclient的使用步骤

3.1 创建httpclient对象

httpclient httpclient = new defaulthttpclient();

3.2 创建httpget(或httppost)对象

httpget httpget = new httpget("https://www.baidu.com");

httppost httppost = new httppost("https://www.baidu.com");

3.3 添加参数(可选)

setparams(httpparams params)//httpget和httppost共有

setentity(httpentity entity)//httppost独有

list params = new arraylist();

params.add(new basicnamevaluepair("age", "20"));

params.add(new basicnamevaluepair("like", "aa"));

params.add(new basicnamevaluepair("like", "bb"));

params.add(new basicnamevaluepair("like", "cc"));

params.add(new basicnamevaluepair("newscategoryid", "1"));

httpentity paramentity = new urlencodedformentity(params,"utf-8");

httppost.setentity(paramentity);

3.4 发送get(或post)请求,并获得响应

httpresponse httpresponse = httpclient.execute(httpurirequest request);

注1:httpurirequest为httpget和httppost的父类

注2:需要添加允许网络访问权限,不然会报错“java.lang.securityexception: permission denied (missing internet permission)”

注3:如果地址错误,或服务器未开户,httpclient这sb会等待n久(>24小时)。

所以请记得设置超时时间,所以请记得设置超时时间,所以请记得设置超时时间

所以请记得设置超时时间,所以请记得设置超时时间,所以请记得设置超时时间

所以请记得设置超时时间,所以请记得设置超时时间,所以请记得设置超时时间

另外httpclient版本不一样,代码也不一样。下面的4.0版本的写法

httpclient.getparams().setparameter(coreconnectionpnames.connection_timeout, 2000);// 连接时间

httpclient.getparams().setparameter(coreconnectionpnames.so_timeout, 2000);// 数据传输时间

3.5 处理响应

3.5.1 响应状态码(200)

httpresponse.getstatusline().getstatuscode()

3.5.2 响应头

getallheaders()/getheaders(string name)

3.5.3 响应内容

httpentity httpentity = httpresponse.getentity();//此对象包含服务器的响应内容

string result = entityutils.tostring(httpentity);

bug

//导入httpclient

uselibrary 'org.apache.http.legacy'

//导入jackson

packagingoptions {

exclude 'meta-inf/dependencies'

exclude 'meta-inf/license'

exclude 'meta-inf/license.txt'

exclude 'meta-inf/license.txt'

exclude 'meta-inf/notice'

exclude 'meta-inf/notice.txt'

exclude 'meta-inf/notice.txt'

exclude 'meta-inf/asl2.0'

}