Skip to content Skip to sidebar Skip to footer

Java.net.protocolexception: Too Many Redirects: 21 Android App

Hello i got the Problem that my app is so slow with this error: java.net.ProtocolException: Too many redirects: 21 Now i dont know why it is soo slow, and gets the error, the only

Solution 1:

Your Android code is perfectly fine - it's the server that's not playing ball. First of all, check that you are calling the correct URL and passing the correct parameters. If all of these are fine, then the problem is definitely on the server side.

If you developed the server code yourself, then post it here and we'll try to help. If it's somebody else's code, then you have to get them to fix it, providing the details of the URL and the error.

Solution 2:

Use HttpClient connection class

org.apache.http.client.HttpClient

instead of HttpURLConnection

HttpClienthttpClient=newDefaultHttpClient();
httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); 
HttpPosthttpPost=newHttpPost("http:\\www.myweb.com"); 
HttpResponseresponse= httpclient.execute(httppost); 
responseBody = "";
BufferedReaderbuffer=newBufferedReader(newInputStreamReader(response.getEntity().getContent()));
Strings="";
while ((s = buffer.readLine()) != null) 
  responseBody += s;

Solution 3:

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:

HttpClienthttpClient=newDefaultHttpClient(); 
Stringurl=http://....;
httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); 
HttpPosthttpPost=newHttpPost(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"); StringEntityrequestBody=newStringEntity(jsonBody);
requestBody.setContentType("application/json");
httpPost.setEntity(requestBody); HttpResponsehttpresponse= httpClient.execute(httpPost); 
org.apache.http.StatusLinestatusRespons= httpresponse.getStatusLine(); 
if ( statusRespons.getStatusCode() > 201 ) { 
    errorText = statusRespons.getStatusCode() + " : " + statusRespons.toString() + " : " +statusRespons.getReasonPhrase() ; 
} 
BufferedReaderbuffer=newBufferedReader(newInputStreamReader(httpresponse.getEntity().getContent(),HTTP.UTF_8), 8); 
Strings=""; while ((s = buffer.readLine()) != null) 
jsonString.append(s);

Solution 4:

In case anyone else is running into this issue, I was using okhttp3 Authenticator in my app. In this particular case, I was attempting to call a login endpoint with incorrect credentials (intentionally), in which case my auth token is empty but I was returning response.request.newBuilder().build() instead of null. Returning null fixed the issue for me.

In other words, don't do this:

classTokenAuthenticator : Authenticator {overridefunauthenticate(route: Route?, response: Response): Request {
        val token = [get token]
        if(token.isNotEmpty()) {
            return response.request.newBuilder()
                .addHeader("Authorization", "Bearer $token")
                .build()
        }

        return response.request.newBuilder().build()
    }
}

Do this:

classTokenAuthenticator : Authenticator {overridefunauthenticate(route: Route?, response: Response): Request? {
        val token = [get token]
        if(token.isNotEmpty()) {
            return response.request.newBuilder()
                .addHeader("Authorization", "Bearer $token")
                .build()
        }

        returnnull
    }
}

Note the return value for the authenticate(route: Route?, response: Response) method is nullable, which did the trick. I had overridden it as non-nullable leading to some confusion.

Post a Comment for "Java.net.protocolexception: Too Many Redirects: 21 Android App"