除了作为FORMPARAM之外,还有其他方法可以将XML文件发送到RESTful Web服务吗?
我的要求是开发一个Web服务,它使用XML文件,将其存储在我的本地机器中,并返回一个声明该文件已被下载/保存的声明。
答案 0 :(得分:2)
这是发布的代码,比SOAP更容易...
// POST the XML string as text/xml via HTTPS
public static String postRequest(String strRequest, String strURL) throws Exception {
String responseXML = null;
try {
URL url = new URL(strURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
byte[] requestXML = strRequest.getBytes();
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length", String.valueOf(requestXML.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Send the String that was read into postByte.
OutputStream out = httpConn.getOutputStream();
out.write(requestXML);
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader br = new BufferedReader(isr);
String temp;
String tempResponse = "";
//Create a string using response from web services
while ((temp = br.readLine()) != null)
tempResponse = tempResponse + temp;
responseXML = tempResponse;
br.close();
isr.close();
} catch (java.net.MalformedURLException e) {
System.out.println("Error in postRequest(): Secure Service Required");
} catch (Exception e) {
System.out.println("Error in postRequest(): " + e.getMessage());
}
return responseXML;
}