【问题标题】:Android HTTP GET request to MongoLab对 MongoLab 的 Android HTTP GET 请求
【发布时间】: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


    【解决方案1】:

    如果您将 URL 直接传递给客户端,则不会自动对其进行编码。

    尝试使用URLEncoder.encode(yourParameter, "UTF-8") 对其进行编码,或使用查询构建器和android.net.Uri.Builder 中的appendQueryParameter 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      相关资源
      最近更新 更多