简体   繁体   English

java.net.ProtocolException: 服务器重定向次数过多 (20)

[英]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;请求 URL ... " http://www.web1.com " 响应代码 ... 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) path=/ 重定向到 URL : " https://www.web2.com " java.net.ProtocolException: 服务器在 sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java) 重定向太多次 (20) :1635) 在 sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) 在 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();在调用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 .我发现这个问题是由于以下原因造成的:当您调用某些 JSON 服务时,有时服务可能会以原始格式或可能不是典型的application/json格式返回您的数据。 Your .openConnection() or InputStreamReader may not be able to read reponse headers and JSON data.您的.openConnection()InputStreamReader可能无法读取响应头和 JSON 数据。

To fix this issue I tried following and it worked for me:为了解决这个问题,我尝试了以下方法,它对我有用:

  • Used HttpClient httpClient = new DefaultHttpClient();使用HttpClient httpClient = new DefaultHttpClient(); instead of (HttpURLConnection) obj.openConnection();而不是(HttpURLConnection) obj.openConnection();

  • Set allow circular redirect: httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);设置允许循环重定向: 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:使用带有 UTF-8 的 StringEntity Read 输入流:

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?希望这对你有帮助?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java.net.Authenticator:java.net.ProtocolException:服务器重定向太多次(20) - java.net.Authenticator : java.net.ProtocolException: Server redirected too many times (20) java.net.ProtocolException: 服务器重定向次数过多 - java.net.ProtocolException: Server redirected too many times 获取“java.net.ProtocolException:服务器重定向次数太多”错误 - Getting “java.net.ProtocolException: Server redirected too many times” Error java.net.ProtocolException:重定向过多:21 Android 应用 - java.net.ProtocolException: Too many redirects: 21 Android App java.net.ProtocolException:Android中的重定向过多 - java.net.ProtocolException: Too many redirects in Android SOAP客户端 - ProtocolException:服务器重定向次数过多 - SOAP client - ProtocolException: Server redirected too many times android中带有HttpsURLConnection的java.net.protocolException - java.net.protocolException with HttpsURLConnection in android 服务器重定向太多次 - Server redirected too many times Java HttpURLConnection问题:服务器重定向次数过多 - Java HttpURLConnection issue: Server redirected too many times 将文件上传到服务器,java.net.ProtocolException:读取响应后无法写入请求正文 - Upload File To Server, java.net.ProtocolException: cannot write request body after response has been read
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM