这是我的第一个问题,所以请耐心等待。
我有一个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) { ... }
答案 0 :(得分:5)
我认为apache提供了所有示例..如果您使用的是httpclient 4,则可以参考此网址http://hc.apache.org/httpcomponents-client-ga/examples.html
此外,您可能会发现这个有用的.. w.r.t设置响应类型等http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
答案 1 :(得分:4)
感谢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) { ... }
答案 2 :(得分:3)
这是您需要的代码段(这取代了您在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
编辑: 以下是posting XML to a server使用Http-Client的示例。