HTTP-запрос для Google Distance Matrix API с использованием Java - PullRequest
0 голосов
/ 18 января 2012

Я хочу сделать следующий HTTP-запрос из моего автономного приложения Java и сохранить выходной файл JSON в моей системе.

Click Me

Как мне это сделать

1 Ответ

1 голос
/ 18 января 2012

Вы пытались использовать java.net.URL, чтобы открыть соединение? (См. JavaDoc ). Я пропустил операторы импорта, но вы поняли:).

URL url = new URL("http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver%20BC%7CSeattle&destinations=San%20Francisco%7CVictoria%20BC&mode=bicycling&language=fr-FR&sensor=false");
ReadableByteChannel inputChannel;
WritableByteChannel outputChannel;
try {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    InputStream urlStream = connection.getInputStream();

    File outputFile = new File("/path/to/output/file");
    inputChannel = Channels.newChannel(urlStream);
    outputChannel = (new FileOutputStream(outputFile)).getChannel();

    outputChannel.transferFrom(inputChannel, 0, connection.getContentLength());
} catch (IOException ioe) {
  // handle your exception here
} finally {
    //check for nulls and stuff before you do this
    inputChannel.close();
    outputChannel.close();
}

Хотя, если вы собираетесь использовать веб-сервисы RESTful, вам может потребоваться изучить Джерси .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...