接続を開いてデータを読み取る前に、リクエスト URL をエンコードしてください。理解を深めるために、以下のコードをご覧ください。
package com.stackoverflow.works;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
public class URLReader {
/*
* @author: sarath_sivan
*/
public static void read(String url) throws IOException {
setProxy();//only invoke this method if you are using any proxy to open connection
URL httpURL = new URL(url);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(httpURL.openStream()));
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
System.out.println(inputLine);
}
bufferedReader.close();
}
public static void setProxy() {
System.getProperties().put("http.proxyHost", "xxx.xxx.xx.xx");//replace with your proxy
System.getProperties().put("http.proxyPort", "8080");
}
public static String encodeURL(String url) throws UnsupportedEncodingException {//encoding your request url parameters here
StringBuilder encodedURL = new StringBuilder(url);
encodedURL.append("?origins=").append(encode("Medical Centre+ 308 George Street+ Sydney"));
encodedURL.append("&destinations=").append(encode(" Science Museum Exhibition Road London SW7 2DD"));
encodedURL.append("&mode=").append("driving");
encodedURL.append("&sensor=").append("false");
return encodedURL.toString();
}
public static String encode(String string) throws UnsupportedEncodingException {
return URLEncoder.encode(string, "ISO-8859-1");
}
public static void main(String[] args) throws IOException {
String url = "http://maps.googleapis.com/maps/api/distancematrix/xml";
read(encodeURL(url));
}
}
出力は次のようになります。