简体   繁体   中英

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

I've this code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class Demo2 {

    public static void main(String[] args) {

        try {

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

    URL obj = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
    conn.setReadTimeout(5000);
    conn.addRequestProperty("Accept-Language", "es-ES,es;q=0.8");
    conn.addRequestProperty("User-Agent", "Mozilla");
    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) {
    System.out.println("Redireccionando...");
    // 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");
    System.out.println("Galletas: " + cookies);

    // open the new connnection again
    conn = (HttpsURLConnection) new URL(newUrl).openConnection();
    conn.setFollowRedirects(true);
    conn.setRequestProperty("Cookie", cookies);
    conn.addRequestProperty("Accept-Language", "es-ES,es;q=0.8");
    conn.addRequestProperty("User-Agent", "Mozilla");       

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

  }

}

and result is:

Request URL ... " http://www.web1.com " Response Code ... 302 Redireccionando... Galletas: 07c18a1bea3520c44535aafeeea31dec07a36313; path=/ Redirect to URL : " https://www.web2.com " java.net.ProtocolException: Server redirected too many times (20) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1635) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) at Demo2.main(Demo2.java:58)

What is the problem? I'm going crazy

I also encountered the same issue and this fix, helped me to overcome it.

before calling the openConnection(); use the following:

HttpURLConnection.setFollowRedirects(false);

I was facing same issue. Even I spent quite a lot amount of time to fix this issue. I found out that issue was coming to due following: When you make a call to some JSON services, sometime services might return you data in raw formats or format which may not be typical application/json . Your .openConnection() or InputStreamReader may not be able to read reponse headers and JSON data.

To fix this issue I tried following and it worked for me:

  • Used HttpClient httpClient = new DefaultHttpClient(); instead of (HttpURLConnection) obj.openConnection();

  • Set allow circular redirect: httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

  • Set following post headers which is important:

     httpPost.setHeader("charset","utf-8"); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Accept-Language","en-US,en;q=0.8"); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

Use StringEntity Read input stream with UTF-8:

httpresponse.getEntity().getContent(),HTTP.UTF_8), 8);

Here is the sample code which worked for me:

HttpClient httpClient = new DefaultHttpClient();
String url =http://....; httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); 
HttpPost httpPost = new HttpPost(url); 
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("charset","utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language","en-US,en;q=0.8");
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
//or you can try httpPost.setContentType("application/x-www-form-urlencoded");
StringEntity requestBody = new StringEntity(jsonBody);
requestBody.setContentType("application/json");
httpPost.setEntity(requestBody);
HttpResponse httpresponse = httpClient.execute(httpPost); 
org.apache.http.StatusLine statusRespons = httpresponse.getStatusLine(); 
if (statusRespons.getStatusCode() > 201)
{
    errorText = statusRespons.getStatusCode() + " : " + statusRespons.toString()  + " : " +statusRespons.getReasonPhrase() ;
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent(),HTTP.UTF_8), 8);
String s = "";
while ((s = buffer.readLine()) != null) 
    jsonString.append(s);

Hope this helps you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM