【发布时间】:2012-12-16 01:39:25
【问题描述】:
我正在编写一个应用程序,它将通过 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 的示例客户端/服务器示例都很棒。
【问题讨论】:
-
那么会发生什么?是否抛出任何异常?如果您可以整理问题中的代码,那将非常有帮助-我估计大约一半的服务器端行是 cmets 或只是空的,并且缩进也被破坏了...
-
我没有收到任何异常,响应状态码为 200,响应正文为空白。
-
那么服务器端的日志显示了什么?您是否设法读取任何字节?
-
我可以读取服务器代码中的xml,但是客户端没有收到任何响应内容。
-
查看答案 - 您期望得到什么响应内容,您认为您的代码在哪里编写响应?