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

当我打印标题字段时,它会显示 500 代码。当我将 URL 更改为 google.com 之类的其他内容时,它可以正常工作。但我不明白为什么它在这里不起作用,但它在浏览器和 curl 上运行良好。

任何帮助将不胜感激..

谢谢,

4

8 回答 8

8

状态码 500 表明 Web 服务器上的代码已崩溃。使用HttpURLConnection#getErrorStream()来了解更多错误信息。参考Http 状态码 500

于 2012-07-30T12:45:52.167 回答
8

这主要是由于编码而发生的。如果您使用浏览器正常,但在您的程序中收到 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"))
于 2014-06-05T00:00:19.240 回答
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,如果我们在 responseCode 中获得重定向:

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;
}
于 2015-04-22T20:32:50.083 回答
1

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

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

于 2012-07-30T12:57:40.817 回答
1

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

于 2017-05-17T12:57:17.900 回答
0

就我而言,事实证明服务器总是为我想要访问的页面返回 HTTP/1.1 500(在浏览器中和在 Java 中一样),但仍然成功地传递了网页内容。

通过浏览器访问特定页面的人不会注意到,因为他会看到页面并且没有错误消息,在 Java 中我必须读取错误流而不是输入流(感谢@Muse)。

不过,我不知道为什么。可能是一些隐蔽的方式来阻止爬虫。

于 2016-06-22T14:29:10.093 回答
0

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

这可能有助于其他相同的情况。

就我而言,我正在本地环境中开发系统,当我从浏览器检查我的 Rest Api 时,一切都运行良好,但我的 Android 系统中一直抛出 HTTP 错误 500。

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

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

于 2016-10-26T11:22:11.153 回答
0

检查参数

httpURLConnection.setDoOutput(false);

仅适用于GETMethod 并设置为trueon POST,这为我节省了很多时间!!!

于 2021-12-21T04:54:30.210 回答