注意使用HttpURLConnection访问网络需要在子线程中操作
public static String loginOfGet(String userName, String password) {
HttpURLConnection conn = null;
try {
String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);
URL url = new URL("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // get或者post必须得全大写
conn.setConnectTimeout(10000); // 连接的超时时间
conn.setReadTimeout(5000); // 读数据的超时时间
int responseCode = conn.getResponseCode();
if(responseCode == 200) {
InputStream is = conn.getInputStream();
String state = getStringFromInputStream(is);
return state;
} else {
Log.i(TAG, "访问失败: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(conn != null) {
conn.disconnect(); // 关闭连接
}
}
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;
}
}
本文提供了一个使用Java通过HTTP GET请求实现登录功能的例子。该示例展示了如何设置URL、进行参数编码、设置请求方法及超时时间,并从服务器获取响应状态码及返回信息。
1317

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



