我在从 Android 应用程序调用简单的 JSON Web 服务时遇到问题。.execute() 以 200-OK 状态成功完成,但是我无法读取任何 JSON 输出或文本。
作为记录,如果我 HttpPost 一个普通网页,比如 Google.com,我可以读取和解析所有标记。此外,我可以从设备的浏览器中调用完整的urlWithParams字符串,并在浏览器中看到 JSON 输出。这适用于设备的浏览器:
当代码运行时,阅读器总是空白并且 reader.readLine() 永远不会运行。返回一个空字符串。如果我将 URL 更改为 Google.com,它会起作用并返回 17,000 个字符。谢谢!
protected String doInBackground(String... uri) {
String responseString = null;
try {
//String urlGoogle = "http://google.com";
//String urlWithParams = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&mode=bicycling&language=fr-FR&sensor=false";
String urlOnly = "http://maps.googleapis.com/maps/api/distancematrix/json";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlOnly);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("origins", "Seattle"));
nameValuePairs.add(new BasicNameValuePair("destinations", "Cleveland"));
nameValuePairs.add(new BasicNameValuePair("sensor", "false"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
responseString = sb.toString();
}}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return responseString;
}