[android,8]8.使用httpclient连接服务端

浏览:
字体:
发布时间:2013-12-22 23:48:35
来源:

 

HttpClient简介:

httpclient 是apache 上的开源项目,是对浏览器的简单包装。

 

一、通过HttpClient发送get请求:

public static StringsendDataByHttpClientGet(String path, String username,String password) throwsException {

// 1.创建一个浏览器 的HttpClient 对象

HttpClient client = newDefaultHttpClient();

// 2.输入一个url ,创建一个url

String urlstr = path +"?name=" + URLEncoder.encode(username)

+"&password=" + URLEncoder.encode(password);

//httpGet对象 表示向指定的url发送get请求

HttpGet httpGet = newHttpGet(urlstr);

// 3.敲一下回车 ;执行get请求,并返回响应的数据

HttpResponse response =client.execute(httpGet);

 

//response.getStatusLine()方法是:获取相应的状态行,

//获取状态行中的状态码。

if(response.getStatusLine().getStatusCode() == 200) {

//response.getEntity()方法获取响应数据的实体。

//获取响应数据的内容

InputStream is = response.getEntity().getContent();

//将流转成文本

byte[] result = StreamTools.getBytes(is);

return new String(result);

}

 

return null;

}

二、通过HttpClient发送post请求:

public static StringsendDataByHttpClientPost(String path, String username,

String password) throws Exception {

// 1.创建一个浏览器

HttpClient client = newDefaultHttpClient();

 

// 2.构建一个post的请求

HttpPost post = newHttpPost(path);

//创建请求实体对象中的参数.就是键值对的集合

Listparameters =

new ArrayList();

parameters.add(newBasicNameValuePair("name", username));

parameters.add(newBasicNameValuePair("password", password));

//创建请求实体对象,并指定字符编码形式。

UrlEncodedFormEntityentity = new UrlEncodedFormEntity(parameters,

"utf-8");

//设置post请求的实体方法

post.setEntity(entity);

 

// 3.敲回车 执行post请求

HttpResponse response =client.execute(post);

//判断响应码

if(response.getStatusLine().getStatusCode() == 200) {

//

InputStream is = response.getEntity().getContent();

byte[] result = StreamTools.getBytes(is);

return new String(result);

}

return null;

}

 

>更多相关文章
24小时热门资讯
24小时回复排行
资讯 | QQ | 安全 | 编程 | 数据库 | 系统 | 网络 | 考试 | 站长 | 关于东联 | 安全雇佣 | 搞笑视频大全 | 微信学院 | 视频课程 |
关于我们 | 联系我们 | 广告服务 | 免责申明 | 作品发布 | 网站地图 | 官方微博 | 技术培训
Copyright © 2007 - 2024 Vm888.Com. All Rights Reserved
粤公网安备 44060402001498号 粤ICP备19097316号 请遵循相关法律法规
');})();