我正在尝试编写一个将通过POST将
XML文件(xml格式化的字符串)发送到另一个servlet的servlet.
(非必需的xml生成代码替换为“Hello there”)
(非必需的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();
解决方法
使用像
HttpClient这样的图书馆,这样的事情就会变得更加简单.甚至有一个
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);