我在 Geolocation API 中收到 FileNotFoundException。我用 google 搜索了一下,发现它只支持 POST 方法,但我已经在 POST 本身中调用了。
请在下面找到我的代码片段,
活动:
String url = "https://www.googleapis.com/geolocation/v1/geolocate?key=API_KEY";
LocationAsyncTask task = new LocationAsyncTask(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
else
task.execute(url);
异步任务:
protected Void doInBackground(String... param) {
HttpsConnectionHelper conn = new HttpsConnectionHelper(weakContext.get());
String response = conn.httpPost(param[0]);
Log.d(MainActivity.LOG_TAG, "LocationAsyncTask = " + response);
return null;
}
Https连接:
String httpPost(String requestURL) {
Log.d(MainActivity.LOG_TAG, "HttpsConnectionHelper# requestURL = " + requestURL);
URL url;
HttpsURLConnection conn = null;
try {
//Create connection
url = new URL(requestURL);
conn = (HttpsURLConnection) url.openConnection();
Log.d(MainActivity.LOG_TAG, "HttpsConnectionHelper# url.openConnection()");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.connect();
Log.d(MainActivity.LOG_TAG, "HttpsConnectionHelper# conn.connect()");
//Get Response
InputStream is = conn.getInputStream();
Log.d(MainActivity.LOG_TAG, "HttpsConnectionHelper# is.available() = "+is.available());
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
Log.d(MainActivity.LOG_TAG, "HttpsConnectionHelper#Exception# e.getMessage() = "+e.getMessage());
} finally {
if (conn != null) {
conn.disconnect();
}
}
return "";
}
编辑
curl -X POST "https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d \
'{ "homeMobileCountryCode":310,
"homeMobileNetworkCode":410,
"radioType":"gsm",
"carrier":"Vodafone",
"considerIp":true
}'
这是来自官方文档。我已经使用这个Curl命令编写了相应的Android代码。
public class GeolocationTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String apiUrl = "https://www.googleapis.com/geolocation/v1/geolocate?key=API_KEY";
Log.d(MainActivity.LOG_TAG, "GeolocationTask# doInBackground() apiUrl = " + apiUrl);
String requestBody = "{ " +
"\"homeMobileCountryCode\":310, " +
"\"homeMobileNetworkCode\":410, " +
"\"radioType\":\"gsm\", " +
"\"carrier\":\"Vodafone\", " +
"\"considerIp\":true " +
"}";
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set up the connection
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
Log.d(MainActivity.LOG_TAG, "GeolocationTask# doInBackground() before write");
// Write the request body
try (OutputStream os = connection.getOutputStream()) {
byte[] input = requestBody.getBytes("utf-8");
os.write(input, 0, input.length);
}
Log.d(MainActivity.LOG_TAG, "GeolocationTask# doInBackground() after write");
// Read the response
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
Log.d(MainActivity.LOG_TAG, "GeolocationTask# doInBackground() response.toString() = "+response.toString());
return response.toString();
}
} catch (IOException e) {
e.printStackTrace();
Log.d(MainActivity.LOG_TAG, "GeolocationTask# doInBackground()# Excep = "+e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Handle the result, e.g., parse the JSON response
if (result != null) {
// Parse and handle the JSON response here
Log.d(MainActivity.LOG_TAG, "LocationAsyncTask(new) = " + result);
}
}
}
但仍然遇到同样的异常。
导致异常的最可能原因是 Geolocation API 作为响应返回给您某种错误。您需要在调用
getInputStream
之前检查响应代码,并相应地处理错误,如下所示:
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
// Get error response
InputStream errorIs = connection.getErrorStream();
processError(errorIs);
} else {
InputStream is = connection.getInputStream();
// do whatever you want
}
您可以阅读 HttpURLConnection.html#getErrorStream Javadoc 了解详细信息,并从 这个问题的答案中获得更多想法。