我正在编写一个应用程序,它将通过 HTTP 将 XML 发送到服务器,并接收 XML 作为响应。我能够将 XML 发送到服务器,但无法接收响应。
这是我的客户代码:
public void sendXMLToServer(){
System.out.println("sendXMLToServer");
String strURL = "http://localhost:9080/MockServerMachine/sendXMLPost";
// Get file to be posted
String strXMLFilename = "output.xml";
File input = new File(strXMLFilename);
// Prepare HTTP post
System.out.println("junaud url "+ strURL);
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
// Per default, the request content needs to be buffered
// in order to determine its length.
// Request body buffering can be avoided when
// content length is explicitly specified
try {
post.setRequestHeader("Content-type","application/xml");
post.setRequestHeader("Accept","application/xml");
post.setRequestEntity(new InputStreamRequestEntity(
new FileInputStream(input), input.length()));
HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(post);
String xmlResponse = post.getResponseBodyAsString();
// Display status code
System.out.println("Response status code jun: " + result);
// Display response
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
post.releaseConnection();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这是服务器端:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//InputStream in = request.getInputStream();
//URL xmlUrl = new URL(request.getRequestURL().toString());
//InputStream in = xmlUrl.openStream();
response.setContentLength(100);
// PostMethod po = new PostMethod(request.getRequestURL().toString());
// System.out.println("kikmk = "+po.getRequestEntity());
try {
// read this file into InputStream
//InputStream inputStream = new FileInputStream("c:\\file.xml");
InputStream inputStream = request.getInputStream();
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File("c:\\junaidAhmedJameel.xml"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
System.out.println(new String (bytes));
System.out.println(read);
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
有谁可以帮我离开这里吗?任何通过 HTTP 发送 XML 的示例客户端/服务器示例都很棒。