对MongoLab的Android HTTP GET请求
问题描述:
我正在开发一个沙箱数据库中的测试应用程序MongoLab
。 当执行一个REST查询,我得到了正确的文件,但在我的Android应用程序抛出异常执行相同的:对MongoLab的Android HTTP GET请求
查询: https://api.mongolab.com/api/1/databases/my-db/collections/my-col?q={id:"123"}&apiKey=***
(当然分贝,山口和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的炭是my-col?q
后的第一=
,并且存在于该行的引用: response = httpclient.execute(new HttpGet(uri[0]));
为什么它在浏览器上运行良好,而不是在我的设备上运行? 虽然我已成功取出所有文件但没有查询,但...
答
如果您将URL直接传递给客户端,它将不会自动编码。
尝试使用URLEncoder.encode(yourParameter, "UTF-8")
对其进行编码或使用的QueryBuilder和从android.net.Uri.Builder
的appendQueryParameter
方法。
感谢它的工作! – itaied