0
我想從我的Java Standalone Application發出以下HTTP請求,並將輸出的JSON文件保存在我的系統中。使用Java的Google Distance Matrix API的HTTP請求
我怎麼做這個
我想從我的Java Standalone Application發出以下HTTP請求,並將輸出的JSON文件保存在我的系統中。使用Java的Google Distance Matrix API的HTTP請求
我怎麼做這個
您是否嘗試過使用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 Web服務公平一點,你可能需要調查Jersey。