Tiago Oliveira
Tiago Oliveira

Reputation: 13

Request by browser gets ok, but request by java got 301

I have a problem when I try to make a Java HTTP request to this URL:

If I request it by browser, I receive a .csv, but when I try a getRequest or postRequest, I get a 301 code.

Here is my code:

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;
}

Upvotes: 1

Views: 729

Answers (1)

Pravin Umamaheswaran
Pravin Umamaheswaran

Reputation: 704

The response is asking you to redirect the request to a new URL. The web browser does it automatically but you will have to do it via code in Java. You can get that redirect location by using:

con.getHeaderField("Location")

Just fire a new Http request using the new URL and you should get the csv file.

Upvotes: 3

Related Questions