-1
響應我有一個Java Web服務,使一個GET請求並期望一個XML響應:從HTTP如何獲取XML值獲得的Java
我的示例代碼如下所示。但是,我無法從響應中消費或獲取xml值。
代碼:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
@WebService(serviceName = "send")
public class send {
@WebMethod(operationName = "recieveFromPhpPortal")
public String recieveFromPhpPortal(@WebParam(name = "name") String DATE, String MSISDN, String PIN) throws IOException {
// Step 1: Construct URL"
String parameters = "VENDOR=D-MXXX&REQTYPE=EXRCTRFREQ&DATA=<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ " <ns0:COMMAND\n"
+ " xmlns:ns0=\"http://safaricom.co.ke/Pinless/keyaccounts/\">\n"
+ " <ns0:TYPE>EXRCTRFREQ</ns0:TYPE>\n"
+ " <ns0:DATE>" + DATE + "</ns0:DATE>\n"
+ " <ns0:EXTNWCODE>SA</ns0:EXTNWCODE>\n"
+ " <ns0:MSISDN>" + MSISDN + "</ns0:MSISDN>\n"
+ " <ns0:PIN>" + PIN + "</ns0:PIN>\n"
+ " </ns0:COMMAND>";
String url = "http://xx.xx.xx.xx/?" + URLEncoder.encode(parameters, "UTF-8");
// Step 2: Call API Url
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
// Step 3: Check the response status
if (responseCode == 200) {
//If response status == 200
System.out.println("The XML HAS been SENT!");
System.out.println("Response Message : " + con.getResponseMessage());
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
//How do I get the XML response and insert into a database
} else {
// print the error received from server
System.out.println("Error in accessing API - " +responseCode);
}
} catch (Exception e) {
throw e;
}
return "Request Received by the webservice For Processing";
}
}
我System.out.println(response.toString());
後獲取XML響應:
<?xml version="1.0"?>
<COMMAND>
<TYPE>EXRCTRFRESP</TYPE>
<TXNSTATUS>Transaction Status</TXNSTATUS >
<DATE>Date and time</DATE>
<EXTREFNUM>Unique</EXTREFNUM>
<TXNID><PreTUPS Transaction ID></TXNID>
<MESSAGE>Transaction Message</MESSAGE>
</COMMAND>
有人請告訴我如何,我可以從響應獲取數據,並保存在數據庫或至少獲取這些響應值TYPE
,EXTREFNUM
,MESSAGE
。
問候。