Java HTTPUrlConnection返回500状态代码
我正在尝试使用HTTPUrlConnection获取URL,但是我总是收到500代码,但是当我尝试从浏览器访问相同的URL或使用curl时,它工作正常!Java HTTPUrlConnection返回500状态代码
这是代码
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表明,在Web服务器的代码已经坠毁。用HttpURLConnection#getErrorStream()获得错误的想法更多。请参考Http Status Code 500
我试过getErrorStream,但它返回空.. – user1069624 2012-07-30 13:30:01
确保您的连接允许以下重定向 - 这是您的连接和浏览器之间行为不同的可能原因之一(默认情况下允许重定向)。
它应该返回代码3xx,但可能有其他地方将其更改为500为您的连接。
emm ..我不认为这是问题,因为我没有重定向时我在浏览器中尝试它..但感谢提示。 – user1069624 2012-07-30 13:32:27
按照Muse的建议从错误流中读取更多错误细节。如果它不是重定向而不是唯一的其他可能性,我可以想到的是服务器在你的请求中需要其他的东西(cookie,其他类型的头文件)。我会复制成功的请求中的浏览器传递的所有头文件(它应该会导致成功的HttpURLConnection调用),而不是按照我的方式一次删除一个头文件。 – 2012-07-30 13:40:30
好吧,我想我知道什么是错的。页面实际上是关闭的,但是从浏览器我认为它用来获得缓存版本..可以这样吗?因为该页面不工作..但是当我尝试在同一主机下的另一个页面..它的工作原理! – user1069624 2012-07-30 14:47:44
这主要是因为编码而发生的。 如果您使用的浏览器正常,但在您的程序中收到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"))
我跑进“网址在浏览器的工作原理的问题,但是当我做HTTP-GET在Java中,我得到一个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;
}
在我的情况下,它变成了服务器总是返回HTTP/1.1 500(在浏览器如在Java中)我想访问的页面,但成功地提供了网页内容。
通过浏览器访问特定页面的人只是没有注意到,因为他会看到页面,没有错误信息,在Java中,我必须读取错误流而不是输入流(谢谢@Muse)。
虽然我不知道为什么。可能会让一些爬行者不知所措。
这是一个老问题,但我有同样的问题,并通过这种方式解决它。
这可能有助于其他情况一样。
在我的情况下,我正在开发本地环境系统,当我从浏览器中检查了我的Rest Api时,每件事情都很好,但我一直在我的Android系统中抛出HTTP错误500。
问题是,当您使用Android时,它在VM(虚拟机)上工作,表示您的本地计算机防火墙可能会阻止您的虚拟机访问本地URL(IP)地址。
你只需要在你的电脑防火墙中允许。如果您尝试从网络外部访问系统,则同样适用。
我面临同样的问题,我们的问题是其中一个参数值中有一个特殊的符号。我们通过使用URLEncoder.encode(String, String)
来修复它是用于内部服务器错误 – 2012-07-30 12:50:23
你试过了什么'theurl'? – sunil 2012-07-30 13:15:11
@sunil我正在尝试http://www.rassd.com/1-23544.htm – user1069624 2012-07-30 13:31:13