2015-08-15 119 views
0

我正在開發一個沙箱數據庫中的測試應用程序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]));

爲什麼它在瀏覽器上運行良好,而不是在我的設備上運行? 雖然我已成功取出所有文件但沒有查詢,但...

回答

1

如果您將URL直接傳遞給客戶端,它將不會自動編碼。

嘗試使用URLEncoder.encode(yourParameter, "UTF-8")對其進行編碼或使用的QueryBuilder和從android.net.Uri.BuilderappendQueryParameter方法。

+0

感謝它的工作! – itaied