我正在的沙盒db中开发一个测试应用程序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中的字符将是第一=
后my-col?q
,且有于该行的引用:response = httpclient.execute(new HttpGet(uri[0]));
为什么在浏览器上而不是在我的设备上能正常工作?我已经成功地拉出了所有文档而没有查询...
如果直接将URL传递给客户端,则不会自动对其进行编码。
尝试使用URLEncoder.encode(yourParameter, "UTF-8")
或使用querybuilder和中的appendQueryParameter
方法对其进行编码android.net.Uri.Builder
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句