我正在尝试编写一个servlet,它将通过POST将XML文件(xml格式化的字符串)发送到另一个servlet.(非必要的xml生成代码替换为"Hello there")
StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + sb.length()); OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write(sb.toString()); outputWriter.flush(); outputWriter.close();
这导致服务器错误,并且永远不会调用第二个servlet.
使用像HttpClient这样的库,这种事情要容易得多.甚至还有一个XML代码示例:
PostMethod post = new PostMethod(url); RequestEntity entity = new FileRequestEntity(inputFile, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); int result = httpclient.executeMethod(post);
我建议使用Apache HTTPClient,因为它是一个更好的API.
但要解决当前的问题:connection.setDoOutput(true);
在打开连接后尝试调用.
StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + sb.length()); OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write(sb.toString()); outputWriter.flush(); outputWriter.close();