private static final String loginUrl = "http://42.120.50.206/apr/login.php";
private String sessionId;
public boolean login(String username, String password) {
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
HttpURLConnection connection = null;
try {
connection = doPost2(loginUrl, params);
if (connection == null) {
return false;
}
String key = "";
if (connection != null) {
for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
//System.out.println("key: " + key);
if (key.equalsIgnoreCase("set-cookie")) {
sessionId = connection.getHeaderField(key);
sessionId = sessionId.substring(0, sessionId.indexOf(";"));
//System.out.println("sessionId: " + sessionId);
}
}
InputStream is = connection.getInputStream();
String result = getResult(is);
System.out.println("result: " + result);
if (sessionId != null) {
return true;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return false;
}
public HttpURLConnection doPost2(String urlStr, Map<String, String> params) throws IOException {
StringBuilder sb = new StringBuilder();
for(Map.Entry<String, String> param : params.entrySet()) {
sb.append(param.getKey()).append("=").append(param.getValue()).append("&");
}
int len = sb.length();
if (len > 0) {
sb.deleteCharAt(len - 1);
}
String args = sb.toString();
//System.out.println("args: " + args);
return doPost2(urlStr, args);
}
/**
* @param args
* @throws IOException
* @throws UnsupportedEncodingException
*/
public HttpURLConnection doPost2(String urlStr, String args) throws IOException {
URL url = null;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// 模仿浏览器,可有可无
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
// 这一行很关键,登录需要这一行
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(10000);
/**
* 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。
* 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:
*/
connection.setDoOutput(true);
//connection.setRequestMethod("POST");
/**
* 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ...
*/
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out.write(args); //向页面传递数据。post的关键所在!
// remember to clean up
out.flush();
out.close();
return connection;
}
private static String getResult(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(
is));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line).append("\r\n");
}
return sb.toString();
}
转载于:https://blog.51cto.com/memory/1288701