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

时间:2013-09-16 22:17:31

标签: java httpurlconnection httpsurlconnection

我有这段代码:

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

  }

}

结果是:

  

请求网址..." http://www.web1.com"   响应代码... 302   Redireccionando ...   Galletas:07c18a1bea3520c44535aafeeea31dec07a36313;   路径= /   重定向到网址:" https://www.web2.com"   java.net.ProtocolException:服务器重定向次数太多(20)at   sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1635)   at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)   在Demo2.main(Demo2.java:58)

有什么问题?我疯了

2 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。即使我花了很多时间来解决这个问题。 我发现该问题将在以下情况发生: 当您调用某些JSON服务时,有时服务可能会以原始格式或格式返回数据,这可能不是典型的application/json。 您的.openConnection()InputStreamReader可能无法读取响应标头和JSON数据。

要解决此问题,我尝试了以下操作,它对我有用:

  • 使用HttpClient httpClient = new DefaultHttpClient();代替 (HttpURLConnection) obj.openConnection();

  • 设置允许循环重定向: httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

  • 设置以下重要的帖子标题:

    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");
    

使用StringEntity使用UTF-8读取输入流:

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

以下是适用于我的示例代码:

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

希望这对你有帮助吗?

答案 1 :(得分:0)

我也遇到了相同的问题,此修复程序帮助我克服了这个问题。

在调用openConnection();之前,请使用以下命令:

HttpURLConnection.setFollowRedirects(false);