1

I'm working with Java 1.7.

When I test the request with Postman in Firefox, I get a response status : 200, and the Json response is good.

When I test it with my Java application, I get this Exception:

java.net.ProtocolException: Server redirected too many times (20)

Here is my java code:

try{
    String charset = "UTF-8";
    URL url = new URL("http://example.com/ws");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET"); 
    con.setRequestProperty("Accept-Charset", charset);
    con.setRequestProperty("token", "mytokenvalue");
    int responseCode = con.getResponseCode();
    BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    System.out.println(response.toString());
}catch(Exception ex){
    ex.printStackTrace();
}

The exception is thrown in this line:

int responseCode = con.getResponseCode();
Marc El Bichon
  • 397
  • 1
  • 7
  • 24

1 Answers1

3

You have to set this property before you open the connection:

HttpURLConnection.setFollowRedirects(false);

Mangu
  • 3,160
  • 2
  • 25
  • 42
Tony N.
  • 76
  • 5