今天做项目,需要跟第三方通信,用第三方的 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"); 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{ ///释放资源 } 注意看粗体,主要是这个头信息设置有误,导致服务器返回 500错误。。 另外,在网上也GOOLGE了下,也有的是说是第二个粗字体处,没有设置的原因,说是安全性。 以此记录下。 原文链接:http://wrong1111./blog/1455191 HttpClient的使用模式:1. 创建一个HttpClient 2.实例化新的HTTP方法,比如PostMethod 或 GetMethod 3.设置HTTP参数名称/值 4.使用HttpClient 执行HTTP调用 5.处理Http响应
如下代码使用HttpClient 获取HttpGet请求:
原文链接:http://ipfire./blog/978063 |
|
来自: 日月桃子 > 《java异常处理》