到公司沒多久,寫了一個java調用.net寫的webService結果期間用各種方法測試都沒有完成,總是拋出異常,最後直接使用SOAP消息去進行調用才成功了,具體代碼如下,僅供參考:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class QueryDataUtil {
public static String getOpdetailString(String regoinId,String regoinName,String signalName) throws Exception{
String xml ="";
xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
xml +="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">";
xml +="<soapenv:Header/>";
xml +="<soapenv:Body>";
xml += "<tem:QueryDeviceRealData><tem:regionId>"+regoinId+"</tem:regionId><tem:regionName>"+regoinName+"</tem:regionName><tem:signalName>"+signalName+"</tem:signalName></tem:QueryDeviceRealData>";
String xml1="</soapenv:Body>";
xml1+="</soapenv:Envelope>";
xml +=xml1;
String urlString="http://IP:端口/xxxx?wsdl";
HttpURLConnection httpConn = null;
OutputStream out = null;
String returnXml="";
//設置批次號
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String s= df.format(new Date());
System.out.println("開始");
httpConn = (HttpURLConnection) new URL(urlString).openConnection();
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", "xxx");
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.connect();
out = httpConn.getOutputStream(); // 獲取輸出流對象
httpConn.getOutputStream().write(xml.getBytes()); // 將要提交服務器的SOAP請求字符流寫入輸出流
out.flush();
out.close();
int code = httpConn.getResponseCode(); // 用來獲取服務器響應狀態
String tempString = null;
StringBuffer sb1 = new StringBuffer();
if (code == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((tempString = reader.readLine()) != null) {
sb1.append(tempString);
}
if (null != reader) {
reader.close();
}
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream(), "UTF-8"));
// 一次讀入一行,直到讀入null為文件結束
while ((tempString = reader.readLine()) != null) {
sb1.append(tempString);
}
if (null != reader) {
reader.close();
}
}
//響應報文
returnXml=sb1.toString();
System.out.println("returnOpdetail==="+returnXml);
return returnXml;
}
}
望大家有什麼意見多多提議哈