gpt4 book ai didi

java - 浏览器请求正常,java请求301

转载 作者:行者123 更新时间:2023-11-29 04:48:42 26 4
gpt4 key购买 nike

当我尝试向 this URL 发出 Java HTTP 请求时遇到问题:

如果我通过浏览器请求它,我会收到一个 .csv,但当我尝试 getRequest 或 postRequest 时,我会收到一个 301 代码。

这是我的代码:

public InputStream sendGet(String url) throws Exception {

String USER_AGENT = "Mozilla/5.0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// optional default is GET
con.setRequestMethod("GET");

//add request header
con.setRequestProperty("User-Agent", USER_AGENT);

int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

InputStream in = con.getInputStream ( ) ;
return in;
}

public InputStream sendPost() throws Exception {

String Url = "http://www.oanda.com/currency/historical-rates/download";
URL obj = new URL(Url);
//HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
HttpURLConnection con2 = (HttpURLConnection) obj.openConnection();
String USER_AGENT = "Mozilla/5.0";
//add reuqest header
con2.setRequestMethod("POST");
con2.setRequestProperty("User-Agent", USER_AGENT);
con2.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = "quote_currency=EUR&end_date=2016-3-26&start_date=2016-3-24&period=daily&display=absolute&rate=0&data_range=c&price=mid&view=graph&base_currency_0=USD&base_currency_1=&base_currency_2=&base_currency_3=&base_currency_4=&download=csv";

// Send post request
con2.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con2.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

int responseCode = con2.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + Url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);

InputStream in = con2.getInputStream() ;
return in;
}

最佳答案

响应要求您将请求重定向到一个新的 URL。 Web 浏览器会自动执行此操作,但您必须通过 Java 代码来执行此操作。您可以使用以下方法获取该重定向位置:

con.getHeaderField("Location")

只需使用新 URL 发出一个新的 Http 请求,您就应该得到 csv 文件。

关于java - 浏览器请求正常,java请求301,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242194/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com