如何用一段简单的java代码获取302跳转前网址的cookie

RT... RT 展开
 我来答
51CTO学院
2015-12-12 · 中国最大的IT实战在线培训平台
51CTO学院
中国最大的IT实战在线教育培训平台。
向TA提问
展开全部
参考:
public static void main(String[] args) {

try {

String url = "http://www.twitter.com";

URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(5000);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");

System.out.println("Request URL ... " + url);

boolean redirect = false;

// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}

System.out.println("Response Code ... " + status);

if (redirect) {

// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");

// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");

// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");

System.out.println("Redirect to URL : " + newUrl);

}

BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();

System.out.println("URL Content... \n" + html.toString());
System.out.println("Done");

} catch (Exception e) {
e.printStackTrace();
}

}
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
百度网友63827ba
2015-12-11 · TA获得超过460个赞
知道小有建树答主
回答量:927
采纳率:55%
帮助的人:322万
展开全部
只能获取Header头的值,然后用一个算法提取cookie即可
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式