今天做項(xiàng)目,需要跟第三方通信,用第三方的 httpclient 可以正常請(qǐng)求。但是換用下面的代碼。確返回 Server returned HTTP response code: 500
當(dāng)時(shí),我一想,不對(duì)呀,第三方請(qǐng)求可以,而且直接用瀏覽器用地址也可以正常訪問,那為什么會(huì)返回提示這個(gè)呢?
前提,頭信息,對(duì)方是 text/xml 編碼 utf-8
代碼如下:
try {
URL urls = new URL(url);
HttpURLConnection uc = (HttpURLConnection) urls.openConnection();
uc.setRequestMethod("POST");
uc.setRequestProperty("ContentType","text/xml;charset=utf-8");
uc.setRequestProperty("charset", "UTF-8");
//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");
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{
///釋放資源
}
注意看粗體,主要是這個(gè)頭信息設(shè)置有誤,導(dǎo)致服務(wù)器返回 500錯(cuò)誤。。
另外,在網(wǎng)上也GOOLGE了下,也有的是說是第二個(gè)粗字體處,沒有設(shè)置的原因,說是安全性。
以此記錄下。
原文鏈接:http://wrong1111.iteye.com/blog/1455191
HttpClient 用于HTTP GET 請(qǐng)求HttpClient的使用模式:
1. 創(chuàng)建一個(gè)HttpClient
2.實(shí)例化新的HTTP方法,比如PostMethod 或 GetMethod
3.設(shè)置HTTP參數(shù)名稱/值
4.使用HttpClient 執(zhí)行HTTP調(diào)用
5.處理Http響應(yīng)
如下代碼使用HttpClient 獲取HttpGet請(qǐng)求:
Java代碼
public class TestHttpGet {
public String executeGet(String url) throws Exception {
BufferedReader in = null;
String content = null;
try {
// 定義HttpClient
HttpClient client = new DefaultHttpClient();
// 實(shí)例化HTTP方法
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
content = sb.toString();
} finally {
if (in != null) {
try {
in.close();// 最后要關(guān)閉BufferedReader
} catch (Exception e) {
e.printStackTrace();
}
}
return content;
}
}
}
原文鏈接:http://ipfire.iteye.com/blog/978063