如何从HttpURLConnection切换到HttpClient

这是我的第一个问题,所以拜托,请耐心等待。

我有一个Swing应用程序,它通过HttpURLConnection从服务器获取XML格式的数据。 现在我正在尝试与服务器创建一个持续的请求 – 响应连接,以检查应用程序是否有任何更新(因为检查必须定期和经常(每隔一秒左右))。

在一些问题的评论中,我读到最好使用Apache HttpClient而不是HttpURLConnection来维护实时连接,但我找不到任何好的例子如何从我当前的代码转到使用HttpClient的代码。 具体来说,使用什么而不是HttpURLConnection.setRequestProperty()和HttpURLConnection.getOutputStream()?

Document request = new Document(xmlElement); Document response = new Document(); String server = getServerURL(datasetName); try { URL url = new URL(server); try { HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestProperty("Content-Type","application/xml; charset=ISO-8859-1"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); OutputStream output = connection.getOutputStream(); XMLOutputter serializer = new XMLOutputter(); serializer.output(request, output); output.flush(); output.close(); InputStream input = connection.getInputStream(); String tempString = ErrOut.printToString(input); SAXBuilder parser = new SAXBuilder(); try { response = parser.build(new StringReader(tempString)); } catch (JDOMException ex) { ... } input.close(); connection.disconnect(); } catch (IOException ex) { ... } } catch (MalformedURLException ex) { ... } 

我认为apache提供了所有的例子..如果你使用的是httpclient 4,你可以参考这个URL http://hc.apache.org/httpcomponents-client-ga/examples.html

另外你可能会发现这个有用的…设置响应类型等等.http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

感谢Santosh和Raveesh Sharma的回答。 我最终使用StringEntity,这就是我现在拥有的:

 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) { ... } 

这是你需要的代码片段(这取代了你在try块中拥有的大部分内容),

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

编辑:这是使用Http-Client将XML发布到服务器的示例。