How to switch from HttpURLConnection to HttpClient

自闭症网瘾萝莉.ら 提交于 2019-12-05 16:22:20

I think apache provides all the examples.. if you are using httpclient 4 you can refer to this URL http://hc.apache.org/httpcomponents-client-ga/examples.html

Additionally you may find this useful.. w.r.t setting the response type etc http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

Thank you Santosh and Raveesh Sharma for your answers. I ended up using StringEntity, and this is what I have now:

Document request = new Document(xmlElement);
Document response = new Document();

XMLOutputter xmlOutputter = new XMLOutputter();
String xml = xmlOutputter.outputString(request);

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(getServerURL(datasetName));
post.setHeader("Content-type", "application/xml; charset=ISO-8859-1");

try
{
  StringEntity se = new StringEntity(xml);
  se.setContentType("text/xml");
  post.setEntity(se);
}
catch (UnsupportedEncodingException e) { ... }

try
{
  HttpResponse httpResponse = client.execute(post);

  BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
  String line = "";
  String tempString = "";
  while ((line = rd.readLine()) != null)
  {
    tempString += line;
  }

  SAXBuilder parser = new SAXBuilder();
  try
  {
    response = parser.build(new StringReader(tempString));
  }
  catch (JDOMException ex) { ... }
}
catch (IOException ex) { ... }

Here is snippet you need (this replaces most of the things you have in try block) ,

try {
String postURL= server;
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(postURL);;
client.executeMethod(postMethod);
InputStream input = postMethod.getResponseBodyAsStream();   
//--your subsequent code here

EDIT: Here is the example of posting XML to a server Using Http-Client.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!