/**
* 使用post的方式登录
* @param userName
* @param password
* @return
*/
public static String loginOfPost(String userName, String password) {
HttpClient client = null;
try {
// 定义一个客户端
client = new DefaultHttpClient();
// 定义post方法
HttpPost post = new HttpPost("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet");
// 定义post请求的参数
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", userName));
parameters.add(new BasicNameValuePair("password", password));
// 把post请求的参数包装了一层.
// 不写编码名称服务器收数据时乱码. 需要指定字符集为utf-8
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
// 设置参数.
post.setEntity(entity);
// 设置请求头消息
// post.addHeader("Content-Length", "20");
// 使用客户端执行post方法
HttpResponse response = client.execute(post); // 开始执行post请求, 会返回给我们一个HttpResponse对象
// 使用响应对象, 获得状态码, 处理内容
int statusCode = response.getStatusLine().getStatusCode(); // 获得状态码
if(statusCode == 200) {
// 使用响应对象获得实体, 获得输入流
InputStream is = response.getEntity().getContent();
String text = getStringFromInputStream(is);
return text;
} else {
Log.i(TAG, "请求失败: " + statusCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client != null) {
client.getConnectionManager().shutdown(); // 关闭连接和释放资源
}
}
return null;
}
HttpClient--HttpClient的Post请求
最新推荐文章于 2024-07-23 15:25:35 发布