我必須創建一個獲取webService響應的方法,如xml
。我知道如何使用Java
類創建,但問題是從webService獲取響應爲xml
。如何從webService響應中獲得響應XML?
這些web服務是基於soap的。
在此先感謝。
我必須創建一個獲取webService響應的方法,如xml
。我知道如何使用Java
類創建,但問題是從webService獲取響應爲xml
。如何從webService響應中獲得響應XML?
這些web服務是基於soap的。
在此先感謝。
我剛剛解決了我的問題。 HttpURLConnection
幫助我。
下面的代碼塊顯示我如何在java
(如Mozilla海報)中獲得xml
響應的海報。
public static void main(String[] args) {
try {
String uri = "http://test.com/IntegratedServices/IntegratedServices.asmx?op=GetUserInfo";
String postData = new XmlTest().xmlRequest("QWERTY10");
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true); // This is important. If you not set doOutput it is default value is false and throws java.net.ProtocolException: cannot write to a URLConnection exception
connection.setRequestMethod("POST"); // This is method type. If you are using GET method you can pass by url. If method post you must write
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); // it is important if you post utf-8 characters
DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); // This three lines is importy for POST method. I wrote preceding comment.
wr.write(postData.getBytes());
wr.close();
InputStream xml = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(xml));
String line = "";
String xmlResponse = "";
while ((line = reader.readLine()) != null) {
xmlResponse += line;
}
File file = new File("D://test.xml"); // If you want to write as file to local.
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(xmlResponse);
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String xmlRequest(String pin) {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
+ " <soap:Body>\n"
+ " <GetUserInfo xmlns=\"http://tempuri.org/\">\n"
+ " <pin>" + pin + "</pin>\n"
+ " </GetUserInfo>\n"
+ " </soap:Body>\n"
+ "</soap:Envelope>";
}
我希望這可以幫助誰想要得到xml
作爲迴應。我還寫了對我的代碼的詳細評論。
用於制肥皂類型的web服務:
休息一下這個鏈接:
我的問題是不解析。我問,我怎樣才能得到答覆作爲XML。我發佈了答案。感謝您的回覆。 –
請分享你至今嘗試過。我們很樂意爲您提供幫助。 – Veeram
@Reddy感謝您的評論。我想在java中創建一個像Mozilla Poster一樣的方法。 –