Rol*_*das 4 java httpclient httpurlconnection
这是我的第一个问题,请耐心等待.
我有一个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) { ... }
Run Code Online (Sandbox Code Playgroud)
我认为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) { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10436 次 |
| 最近记录: |