java http 302重定向_Java 纯HTTP请求 禁止302自动重定向
Java 純HTTP Get請(qǐng)求獲取響應(yīng)內(nèi)容,如果發(fā)生302重定向,繼而模擬請(qǐng)求域獲取重定向后的響應(yīng)內(nèi)容。
關(guān)鍵點(diǎn):設(shè)置conn.setInstanceFollowRedirects為false即可
示例代碼
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer();
String url = "http://localhost:8080/istock/login?u=name&p=pass";
System.out.println("訪問(wèn)地址:" + url);
//發(fā)送get請(qǐng)求
URL serverUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
conn.setRequestMethod("GET");
//必須設(shè)置false,否則會(huì)自動(dòng)redirect到重定向后的地址
conn.setInstanceFollowRedirects(false);
conn.addRequestProperty("Accept-Charset", "UTF-8;");
conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
conn.addRequestProperty("Referer", "http://matols.com/");
conn.connect();
//判定是否會(huì)進(jìn)行302重定向
if (conn.getResponseCode() == 302) {
//如果會(huì)重定向,保存302重定向地址,以及Cookies,然后重新發(fā)送請(qǐng)求(模擬請(qǐng)求)
String location = conn.getHeaderField("Location");
String cookies = conn.getHeaderField("Set-Cookie");
serverUrl = new URL(location);
conn = (HttpURLConnection) serverUrl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Charset", "UTF-8;");
conn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
conn.addRequestProperty("Referer", "http://matols.com/");
conn.connect();
System.out.println("跳轉(zhuǎn)地址:" + location);
}
//將返回的輸入流轉(zhuǎn)換成字符串
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 釋放資源
inputStream.close();
inputStream = null;
System.out.println(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
相關(guān)文章:
總結(jié)
以上是生活随笔為你收集整理的java http 302重定向_Java 纯HTTP请求 禁止302自动重定向的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 房贷20万10年多少利息
- 下一篇: 养老目标基金怎么购买 4种途径供你选择