今天做项目,需要跟第三方通信,用第三方的 httpclient 可以正常请求。但是换用下面的代码。确返回 Server returned HTTP response code: 500
当时,我一想,不对呀,第三方请求可以,而且直接用浏览器用地址也可以正常访问,那为什么会返回提示这个呢?
前提,头信息,对方是 text/xml 编码 utf-8
代码如下:
try {
URL urls = new URL(url);
HttpURLConnection uc = (HttpURLConnection) urls.openConnection();
uc.setRequestMethod("POST");
[color=red][b]uc.setRequestProperty("ContentType","text/xml;charset=utf-8");[/b][/color]
uc.setRequestProperty("charset", "UTF-8");
[color=red][i]
//uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT //5.1)AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.46 Safari/535.11");[/i][/color]
uc.setDoOutput(true);
uc.setDoInput(true);
//uc.setReadTimeout(10000);
//uc.setConnectTimeout(10000);
if(!StringUtils.isBlank(message)){
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
dos.write(message.getBytes("UTF-8"));
dos.flush();
}
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
String readLine = "";
while ((readLine = in.readLine()) != null) {
sb.append(readLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
///释放资源
}
注意看粗体,主要是这个头信息设置有误,导致服务器返回 500错误。。
另外,在网上也GOOLGE了下,也有的是说是第二个粗字体处,没有设置的原因,说是安全性。
以此记录下。
当时,我一想,不对呀,第三方请求可以,而且直接用浏览器用地址也可以正常访问,那为什么会返回提示这个呢?
前提,头信息,对方是 text/xml 编码 utf-8
代码如下:
try {
URL urls = new URL(url);
HttpURLConnection uc = (HttpURLConnection) urls.openConnection();
uc.setRequestMethod("POST");
[color=red][b]uc.setRequestProperty("ContentType","text/xml;charset=utf-8");[/b][/color]
uc.setRequestProperty("charset", "UTF-8");
[color=red][i]
//uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT //5.1)AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.46 Safari/535.11");[/i][/color]
uc.setDoOutput(true);
uc.setDoInput(true);
//uc.setReadTimeout(10000);
//uc.setConnectTimeout(10000);
if(!StringUtils.isBlank(message)){
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
dos.write(message.getBytes("UTF-8"));
dos.flush();
}
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
String readLine = "";
while ((readLine = in.readLine()) != null) {
sb.append(readLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
///释放资源
}
注意看粗体,主要是这个头信息设置有误,导致服务器返回 500错误。。
另外,在网上也GOOLGE了下,也有的是说是第二个粗字体处,没有设置的原因,说是安全性。
以此记录下。