Как перейти с HttpURLConnection на HttpClient - PullRequest
4 голосов
/ 16 декабря 2011

это мой первый вопрос, поэтому, пожалуйста, потерпите меня.

У меня есть приложение Swing, которое получает данные в формате XML с сервера через HttpURLConnection. Сейчас я пытаюсь создать постоянное соединение типа «запрос-ответ» с сервером, чтобы проверить, есть ли какие-либо обновления для приложения (поскольку проверка должна выполняться регулярно и часто (каждую секунду или около того)).

В комментарии к одному вопросу я прочитал, что было бы лучше использовать 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) { ... }

Ответы [ 3 ]

5 голосов
/ 16 декабря 2011

Я думаю, что apache предоставляет все примеры .. если вы используете httpclient 4, вы можете обратиться к этому URL http://hc.apache.org/httpcomponents-client-ga/examples.html

Кроме того, вы можете найти это полезным .. w.r.t установка типа ответа и т. Д. http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

4 голосов
/ 23 декабря 2011

Спасибо, Сантош и Равиш Шарма, за ваши ответы.В итоге я использовал 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) { ... }
3 голосов
/ 16 декабря 2011

Вот фрагмент кода, который вам нужен (он заменяет большинство вещей, которые есть в блоке 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

EDIT: Вот пример отправки XML на сервер Использование Http-клиента.

...