【发布时间】:2015-11-08 13:10:00
【问题描述】:
我正在MongoLab 的沙盒数据库中开发一个测试应用程序。
执行 REST 查询时,我得到了正确的文档,但在我的 Android 应用程序中执行相同的查询会引发异常:
查询:
https://api.mongolab.com/api/1/databases/my-db/collections/my-col?q={id:"123"}&apiKey=***
(当然定义了 db、col 和 api 键)。
将此 URI 放入浏览器中会返回我要查找的文档。
安卓:
class RequestTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... uri) {
Log.i("URI", uri[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.e(LOG_TAG, e.getMessage());
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage());
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(LOG_TAG, result);
}
}
例外:
java.lang.RuntimeException: An error occured while executing doInBackground()
...
Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 71: https://api.mongolab.com/api/1/databases/my-db/collections/my-col?q={"id":"123"}&apiKey=***
索引71处的char是my-col?q之后的第一个=,有对这一行的引用:
response = httpclient.execute(new HttpGet(uri[0]));
为什么它在浏览器上运行良好而不是在我的设备上运行? 我已经成功地提取了所有文档而无需查询...
【问题讨论】:
标签: android rest httprequest mlab