热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

HttpClient发起GET/POST请求

在工作线程中进行此操作:GET请求:publicStringloginOfGet(Stringusername,Stringpassword){HttpCl

在工作线程中进行此操作:

GET请求:

public String loginOfGet(String username, String password) {
HttpClient client = null;
try {
// 定义客户端对象
client = new DefaultHttpClient();
// 声明Get方法
String uri = "http://xxx?";
String data = "username=" + username + "&password=" + password;
HttpGet get = new HttpGet(uri + data);
// 使用客户端执行Get方法
HttpResponse respOnse= client.execute(get);
// 获得响应码,处理服务器返回的数据
int stateCode = response.getStatusLine().getStatusCode();
if (200 == stateCode) {
InputStream is = response.getEntity().getContent();
// 解析服务器返回的数据
String result = getStringFromInputStream(is);
return result;
} else {

}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client != null){
// 断开连接,释放资源
client.getConnectionManager().shutdown();
}
}
return null;
}

POST请求:

public String loginOfPost(String username, String password) {
HttpClient client = null;
try {
// 定义客户端对象
client = new DefaultHttpClient();
// 声明Post方法
String uri = "http://xxx?";
HttpPost post = new HttpPost(uri);

// 定义post的请求的参数
List parameters = new ArrayList();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
// 包装post请求的参数
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
// 设置参数
post.setEntity(entity);

// 使用客户端执行Post方法
HttpResponse respOnse= client.execute(post);
// 获得响应码,处理服务器返回的数据
int stateCode = response.getStatusLine().getStatusCode();
if (200 == stateCode) {
InputStream is = response.getEntity().getContent();
// 解析服务器返回的数据
String result = getStringFromInputStream(is);
return result;
} else {

}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client != null){
// 断开连接,释放资源
client.getConnectionManager().shutdown();
}
}
return null;
}


/**
* 根据流返回一个字符串信息
*/

private String getStringFromInputStream(InputStream is) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;

while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
is.close();
String html = baos.toString(); // 把流中的数据转换成字符串, 采用的编码是: utf-8
// String html = new String(baos.toByteArray(), "GBK");
baos.close();
return html;
}

推荐阅读
author-avatar
sdfaghasfdg4
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有