用HttpClient写入正文请求

我想用XML内容types写一个请求的主体,但我不知道如何与HttpClient对象( http://hc.apache.org/httpclient-3.x/apidocs/index.html )

DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpRequest = new HttpPost(this.url); httpRequest.setHeader("Content-Type", "application/xml"); 

而我不知道如何继续用我的XML写身体…

如果你的xml是用java.lang.String写的,那么你可以用这种方式来使用HttpClient

  public void post() throws Exception{ HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.baidu.com"); String xml = "<xml>xxxx</xml>"; HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8")); post.setEntity(entity); HttpResponse response = client.execute(post); String result = EntityUtils.toString(response.getEntity()); } 

注意例外。

顺便说一句,这个例子是由httpclient版本4.x编写的

扩展你的代码(假设你想发送的XML是在xmlString ):

 String xmlString = "</xml>"; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpRequest = new HttpPost(this.url); httpRequest.setHeader("Content-Type", "application/xml"); StringEntity xmlEntity = new StringEntity(xmlString); httpRequest.setEntity(xmlEntity ); HttpResponse httpresponse = httpclient.execute(httppost);