您可以在打开连接以读取数据之前对请求 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));
}
}
输出如下所示: