发送GET请求时为什么会出现错误500?

时间:2011-05-22 15:47:14

标签: java

我正在尝试发送一个简单的GET请求,如下所述:Using java.net.URLConnection to fire and handle HTTP requests

我指向的网页是:https://e-campus.hei.fr/ERP-prod/

我收到HTTP500错误:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: https://e-campus.hei.fr/ERP-prod/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at GetWebPage.main(GetWebPage.java:14)

为什么我收到此页面的错误?我写的代码将返回任何其他网页的源代码...

我的代码:

public class GetWebPage {
public static void main(String args[]) throws MalformedURLException,
        IOException {
    URLConnection connection = new URL("https://e-campus.hei.fr/ERP-prod/").openConnection();
    connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401");
    InputStream response = connection.getInputStream();

    InputStreamReader isr = new InputStreamReader(response);
    BufferedReader reader = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    String line = "";
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    System.out.println(sb.toString());

}

}

3 个答案:

答案 0 :(得分:2)

标准java.net.URL类不支持HTTPS协议。 您必须设置系统属性并向Security类对象添加新的安全提供程序。有两种方法可以做到这两件事,但试试这个:

System.setProperty("java.protocol.handler.pkgs",
        "com.sun.net.ssl.internal.www.protocol");
   Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

如果与443不同,则附加端口号

URL url = new URL("https://[your server]:7002");

   URLConnection con = URL.openConnection();
   //SSLException thrown here if server certificate is invalid
   con.getInputStream();

如果证书不受信任,你必须抓住SSLException ...

最终代码如下所示:

System.setProperty("java.protocol.handler.pkgs", 
      "com.sun.net.ssl.internal.www.protocol"); 
    try
    {
    //if we have the JSSE provider available, 
    //and it has not already been
    //set, add it as a new provide to the Security class.
    Class clsFactory = Class.forName("com.sun.net.ssl.internal.ssl.Provider");
    if( (null != clsFactory) && (null == Security.getProvider("SunJSSE")) )
        Security.addProvider((Provider)clsFactory.newInstance());
    }
    catch( ClassNotFoundException cfe )
    {
      throw new Exception("Unable to load the JSSE SSL stream handler." +  
        "Check classpath."  + cfe.toString());
    }


   URL url = new URL("https://[your server]:7002");
   URLConnection con = URL.openConnection();
   //SSLException thrown here if server certificate is invalid
   con.getInputStream();

答案 1 :(得分:1)

错误500表示服务器端出错。这通常是由服务器上的脚本生成无效响应头(通常由脚本生成异常引起)引起的。您的IOException是因为您的代码未设置为处理这些错误代码。

答案 2 :(得分:1)

该错误表示“内部服务器错误”。我认为这可能是由对SSL主机的常规请求引起的(请参阅url中的httpS前缀)。您可能没有发送有效的HTTPS请求,并且服务器通过引发未处理的错误来错误地处理此问题。