Write data from one java servlet to another

I'm trying to write a servlet that will post an XML file (an XML formatted string) to another servlet

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();

This causes a server error and never calls the second servlet

Solution

Using a library like httpclient makes things easier There is even a post XML code example:

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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>