java 登录牵手_Java: HttpURLConnection 模拟登录方法 (带cookie 的Post/Get)_20160908_七侠镇莫尛貝...
// http://blog.csdn.net/woxueliuyun/article/details/43267365
package tool
class MyHttpUrlConn {
public static String cookieVal=""
public static void Get(String url_get,String str_param_url,String charset,String cookie) throws IOException {
// 拼湊get請(qǐng)求的URL字串,使用URLEncoder.encode對(duì)特殊和不可見(jiàn)字符進(jìn)行編碼
// String getURL = GET_URL + "?username=" + URLEncoder.encode("fat man", "utf-8");
String getURL = url_get + "?" + str_param_url
URL getUrl = new URL(getURL);
// 根據(jù)拼湊的URL,打開連接,URL.openConnection函數(shù)會(huì)根據(jù)URL的類型,
// 返回不同的URLConnection子類的對(duì)象,這里URL是一個(gè)http,因此實(shí)際返回的是HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
if (cookie != null) {
//發(fā)送cookie信息上去,以表明自己的身份,否則會(huì)被認(rèn)為沒(méi)有權(quán)限
println("set cookieVal = [" + cookie + "]")
connection.setRequestProperty("Cookie", cookie);
}
// 進(jìn)行連接,但是實(shí)際上get request要在下一句的connection.getInputStream()函數(shù)中才會(huì)真正發(fā)到
// 服務(wù)器
connection.connect();
// 取得輸入流,并使用Reader讀取
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(),charset));
System.out.println("Contents of get request:");
String lines;
while ((lines = reader.readLine()) != null) {
System.out.println(lines);
}
println(" ")
reader.close();
// 斷開連接
connection.disconnect();
}
public static String Post(String url_post,String str_param_body,String charset,boolean b_flag,String cookies) throws IOException {
// Post請(qǐng)求的url,與get不同的是不需要帶參數(shù)
URL postUrl = new URL(url_post);
// 打開連接
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
// Output to the connection. Default is
// false, set to true because post
// method must write something to the
// connection
// 設(shè)置是否向connection輸出,因?yàn)檫@個(gè)是post請(qǐng)求,參數(shù)要放在
// http正文內(nèi),因此需要設(shè)為true
if("" != cookies){
connection.setRequestProperty("Cookie", cookies);
}
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// Set the post method. Default is GET
connection.setRequestMethod("POST");
// Post cannot use caches
// Post 請(qǐng)求不能使用緩存
connection.setUseCaches(false);
// This method takes effects to
// every instances of this class.
// URLConnection.setFollowRedirects是static函數(shù),作用于所有的URLConnection對(duì)象。
// connection.setFollowRedirects(true);
// This methods only
// takes effacts to this
// instance.
// URLConnection.setInstanceFollowRedirects是成員函數(shù),僅作用于當(dāng)前函數(shù)
connection.setInstanceFollowRedirects(b_flag);
// Set the content type to urlencoded,
// because we will write
// some URL-encoded content to the
// connection. Settings above must be set before connect!
// 配置本次連接的Content-type,配置為application/x-www-form-urlencoded的
// 意思是正文是urlencoded編碼過(guò)的form參數(shù),下面我們可以看到我們對(duì)正文內(nèi)容使用URLEncoder.encode
// 進(jìn)行編碼
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成,
// 要注意的是connection.getOutputStream會(huì)隱含的進(jìn)行connect。
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
// The URL-encoded contend
// 正文,正文內(nèi)容其實(shí)跟get的URL中'?'后的參數(shù)字符串一致
// String content = "userName=" + URLEncoder.encode("console", "utf-8");
// content = content + "&password=" + URLEncoder.encode("12345678", "utf-8");
println("http param body = [" + str_param_body + "]")
// DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫道流里面
out.writeBytes(str_param_body);
out.flush();
// 取得cookie,相當(dāng)于記錄了身份,供下次訪問(wèn)時(shí)使用
// cookieVal = connection.getHeaderField("Set-Cookie").split(";")[0]
cookieVal = connection.getHeaderField("Set-Cookie")
println("get cookieVal = [" + cookieVal + "]")
out.close(); // flush and close
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(),charset));
String line;
System.out.println("Contents of post request:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
println(" ")
reader.close();
connection.disconnect();
return cookieVal
}
}
用法:
String cookie_login = MyHttpUrlConn.Post(URL_LOGIN,"userName=admin&password=12345678","utf-8",false,"");
MyHttpUrlConn.Post(URL_POST_SAVE,"name=mxb&yearsold=6","utf-8",false,cookie_login);
MyHttpUrlConn.Get(URL_GET_VIEW,"name=mxb&yearsold=6","utf-8",cookie_login);
說(shuō)明:
向URL_POST_SAVE Post數(shù)據(jù)時(shí),要帶上URL_LOGIN時(shí)生成的cookie,否則無(wú)法save數(shù)據(jù)。
同理Get也是。
總結(jié)
以上是生活随笔為你收集整理的java 登录牵手_Java: HttpURLConnection 模拟登录方法 (带cookie 的Post/Get)_20160908_七侠镇莫尛貝...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: promise链式调用_这一次,彻底弄懂
- 下一篇: java 图片不能正常移动_Java,我