【发布时间】:2015-03-12 23:36:28
【问题描述】:
我一直在尝试使用 Google api,更具体地说是这个 URL 来获取美国州和城市,我不断收到 403 Forbidden HTTP 错误消息,我的代码如下:
private static boolean getAddressResult(String input, StringBuilder jsonResults) {
HttpURLConnection conn = null;
try {
String mapUrl;
StringBuilder sb = new StringBuilder(https://maps.googleapis.com/maps/api/geocode/json);
sb.append("?sensor=false&address=" + URLEncoder.encode(input, "utf8"));
mapUrl = sb.toString();
URL url = new URL(mapUrl);
Logger.d(TAG, ""+ url);
Logger.d(TAG, "trying to read");
conn = (HttpURLConnection) url.openConnection();
int status = conn.getResponseCode();
Logger.d(TAG, "status: "+ status);
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
long currentTime = System.currentTimeMillis();
while ((read = in.read(buff)) != -1) {
Logger.d("NetworkUtil", "trying to parse");
long elapsedTime = System.currentTimeMillis();
if(elapsedTime-currentTime>=5000)
return false;
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Logger.e(LOG_TAG, "Error processing Places API URL", e);
return true;
} catch (IOException e) {
Logger.e(LOG_TAG, "Error connecting to Places API", e);
return true;
} finally {
if (conn != null) {
conn.disconnect();
}
}
return false;
}
我尝试了不同的替代方法,包括将 URL 从 HTTP 更改为 HTTPS,我不确定此时我究竟缺少什么,很少有此 Web 服务调用返回 200 成功但大多数情况下它只是失败并出现 403 HTTP 错误代码的时间,此时任何建议都会有所帮助,我还附上了来自 Logcat 的日志:
Error connecting to Places API
java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=08080
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
at .getAddressResult(NetworkUtil.java:217)
at .access$000(NetworkUtil.java:30)
at $ResolveCityTask.doInBackground(NetworkUtil.java:81)
at $ResolveCityTask.doInBackground(NetworkUtil.java:42)
【问题讨论】:
-
可能没有网络连接?
标签: java android web-services google-maps http-status-code-403