/**
* 使用get的方式登录
* @param userName
* @param password
* @return 登录的状态
*/
public static String loginOfGet(String userName, String password) {
HttpClient client = null;
try {
// 定义一个客户端
client = new DefaultHttpClient();
// 定义一个get请求方法
String data = "username=" + userName + "&password=" + password;
HttpGet get = new HttpGet("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data);
// response 服务器相应对象, 其中包含了状态信息和服务器返回的数据
HttpResponse response = client.execute(get); // 开始执行get方法, 请求网络
// 获得响应码
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;
}
/**
* 根据流返回一个字符串信息
* @param is
* @return
* @throws IOException
*/
private static String getStringFromInputStream(InputStream is) throws IOException {
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;
}