在工作线程中进行此操作:
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<NameValuePair> parameters = new ArrayList<NameValuePair>();
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;
}
本文介绍如何使用HttpClient通过GET和POST方式发送登录请求,并解析服务器返回的数据。文章详细展示了两种请求方式的具体实现代码。
765

被折叠的 条评论
为什么被折叠?



