Java HTTPUrlConnection返回500状态码

8

我正在尝试使用HTTPUrlConnection获取一个url,但是我总是得到一个500代码的错误,但是当我尝试从浏览器或使用curl访问同样的url时,它可以正常工作!

以下是代码:

try{
    URL url = new URL("theurl"); 
    HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
    httpcon.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    httpcon.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:14.0) Gecko/20100101 Firefox/14.0.1");
    System.out.println(httpcon.getHeaderFields());
    }catch (Exception e) {
        System.out.println("exception "+e);
    }

当我打印headerfields时,显示500代码... 当我将URL更改为像google.com这样的其他内容时,它可以正常工作。但我不明白为什么在此处不起作用,但在浏览器和curl中可以正常工作。
非常感谢任何帮助...
谢谢,

500 表示内部服务器错误。 - Abhishek bhutra
你尝试过的 theurl 是什么? - sunil
@sunil 我正在尝试访问http://www.rassd.com/1-23544.htm - user1069624
8个回答

9

这主要是由于编码问题引起的。如果您在浏览器中使用正常,但在程序中出现500(内部服务器错误),那么这是因为浏览器对字符集和内容类型有高度复杂的代码。

以下是我的代码,在ISO8859_1字符集和英语语言情况下有效。

public void sendPost(String Url, String params) throws Exception {


    String url=Url;
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestProperty("Acceptcharset", "en-us");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("charset", "EN-US");
    con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    String urlParameters=params;
    // Send post request
    con.setDoOutput(true);
    con.setDoInput(true);
    con.connect();
    //con.

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());
    this.response=response.toString();
    con.disconnect();

}

在主程序中,像这样调用它:

并在主程序中,这样调用:

myclassname.sendPost("https://change.this2webaddress.desphilboy.com/websitealias/orwebpath/someaction","paramname="+URLEncoder.encode(urlparam,"ISO8859_1"))

8

2
我遇到了一个问题:"在浏览器中可以正常访问URL,但是用Java的http-get方法访问时会出现500错误"。
这种情况下,我的问题是:普通的http-get请求在/default.aspx和/login.aspx之间进入了无限重定向循环。
        URL oUrl = new URL(url);
        HttpURLConnection con = (HttpURLConnection) oUrl.openConnection();
        con.setRequestMethod("GET");
        ...
        int responseCode = con.getResponseCode();

发生的情况是:服务器提供了一个由三部分组成的cookie,而con.getResponseCode()只使用了其中一部分。头部中的cookie数据如下:

header.key = null
     value = HTTP/1.1 302 Found
...
header.key = Location
     value = /default.aspx
header.key = Set-Cookie
     value = WebCom-lbal=qxmgueUmKZvx8zjxPftC/bHT/g/rUrJXyOoX3YKnYJxEHwILnR13ojZmkkocFI7ZzU0aX9pVtJ93yNg=; path=/
     value = USE_RESPONSIVE_GUI=1; expires=Wed, 17-Apr-2115 18:22:11 GMT; path=/
     value = ASP.NET_SessionId=bf0bxkfawdwfr10ipmvviq3d; path=/; HttpOnly
...

因为服务器只收到了所需数据的三分之一,所以它变得混乱了:你已经登录了!不,等等,你需要登录。不,你已经登录了...

为了解决无限重定向循环的问题,我不得不手动查找重定向并手动解析头部中的“Set-cookie”条目。

            con = (HttpURLConnection) oUrl.openConnection();
            con.setRequestMethod("GET");
            ...
            log.debug("Disable auto-redirect. We have to look at each redirect manually");
            con.setInstanceFollowRedirects(false);
            ....
            int responseCode = con.getResponseCode();

使用这段代码,如果我们在响应代码中收到重定向,则解析cookie:
private String getNewCookiesIfAny(String origCookies, HttpURLConnection con) {
    String result = null;
    String key;
    Set<Map.Entry<String, List<String>>> allHeaders = con.getHeaderFields().entrySet();
    for (Map.Entry<String, List<String>> header : allHeaders) {
        key = header.getKey();

        if (key != null && key.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) {
            // get the cookie if need, for login
            List<String> values = header.getValue();
            for (String value : values) {
                if (result == null || result.isEmpty()) {
                    result = value;
                } else {
                    result = result + "; " + value;
                }
            }
        }
    }
    if (result == null) {
        log.debug("Reuse the original cookie");
        result = origCookies;
    }
    return result;
}

1

请确保您的连接允许跟随重定向 - 这是您的连接和浏览器之间行为差异的可能原因之一(默认情况下允许重定向)。

它应该返回代码3xx,但可能有其他地方会将其更改为500以适应您的连接。


嗯,我不认为这是问题,因为当我在浏览器中尝试时没有重定向..但还是谢谢你的提示。 - user1069624
请按照Muse的建议从错误流中读取更多错误详细信息。如果没有重定向,那么我能想到的唯一可能性是服务器期望您的请求中包含其他内容(cookie、其他类型的标头)。我会复制浏览器在成功请求中传递的所有标头(这应该会导致成功的HttpURLConnection调用),然后逐个删除标头。 - Germann Arlington
好的,我觉得我知道问题出在哪里了。这个页面实际上已经挂掉了,但我想浏览器之前可能已经缓存了它的版本。这可能是原因吗?因为这个页面根本无法工作,但当我尝试同一主机下的另一个页面时,它可以工作! - user1069624
1
好的,这种情况经常发生。为了测试目的,我总是将浏览器设置为忽略缓存,并在每次重新从服务器获取数据。 - Germann Arlington

1

我遇到了同样的问题,我们的问题是参数值中有一个特殊符号。我们通过使用URLEncoder.encode(String, String)来解决了这个问题。


0

检查参数

httpURLConnection.setDoOutput(false);

仅适用于 GET 方法并在 POST 上设置为 true,这节省了我很多时间!!!


0
在我的情况下,服务器总是以 HTTP/1.1 500 的形式返回(在浏览器和 Java 中),但仍然成功地传递了网页内容。
通过浏览器访问特定页面的人不会注意到这一点,因为他将看到页面而没有错误消息,在Java中,我必须读取错误流而不是输入流(感谢@Muse)。
虽然我不知道原因,但可能是某种模糊的方法来防止网络爬虫。

0

这是一个老问题,但我曾经遇到过同样的问题,并以这种方式解决了它。

这可能会帮助其他处于相同情况的人。

在我的情况下,我正在本地环境中开发系统,当我从浏览器检查我的 Rest Api 时,一切都正常,但是在我的 Android 系统中,我一直收到 HTTP 错误 500。

问题在于当您在 Android 上工作时,它在 VM(虚拟机)上运行,也就是说,这意味着您的本地计算机防火墙可能会阻止您的虚拟机访问本地 URL(IP)地址。

您只需要在计算机防火墙中允许即可。如果您尝试从网络外部访问系统,则同样适用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接