最近项目上要求调用异地的WebService,以前有写过xfire WebService,就按照原先的写了,发现掉不同,后来发现对面写的WebServcie是使用.NET语言写的,且传输的是对象,愁了三天,相继使用了XFIRE,以及CXF,AXIS调用,都不行,各种错误。后来就想使用基础的,java自带的HttpConnection提交其XML数据,后来开始也是掉不同,出现错误如下:
java.io.IOException: Server returned HTTP response code: 500 for URL:
后来从网上找原因都说是要求增加如下代码:
connectioin.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
试了不行,后来辗转多地,找到如下方法,试了,可以
con.setRequestProperty("SOAPAction", "相应的soapaction");、
源代码如下:
/**
* 以post的方式模拟HTTP
* @param urlStr
* @param paras
* @return
*/
public String httpPost(String urlStr, String paras) {
byte[] data = paras.getBytes();
URL url = null;
HttpURLConnection con = null;
InputStream input = null;
String response = null;
try {
url = new URL(urlStr);
con = (HttpURLConnection)url.openConnection();
con.setConnectTimeout(1000 * 6);
//Server returned HTTP response code: 500 for URL:错误解决方案
con.setRequestProperty("SOAPAction", "http://tempuri.org/IInsureBill/Submit");
con.setDoInput(true);
con.setDoOutput(true);
//如果为 true,则只要有条件就允许协议使用缓存
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Length", String.valueOf(data.length));
con.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
con.connect();
DataOutputStream outputStream = new DataOutputStream(con.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
int responseCode = con.getResponseCode();
if(responseCode == 200) {
input = con.getInputStream();
response = getResponse(input);
}else {
input = con.getInputStream();
response = getResponse(input);
System.out.println(response);
response = "返回码为:"+responseCode;
}
}catch(Exception e) {
e.printStackTrace();
}finally {
con.disconnect();
}
return response;
}