2015-08-15 5 views
0

Я разрабатываю тестовое приложение в песочнице db по адресу MongoLab. При выполнении запроса REST я получаю правильный документ, но выполнение той же в моем Android приложение исключением броска:Android HTTP GET запрос на MongoLab

Запрос: https://api.mongolab.com/api/1/databases/my-db/collections/my-col?q={id:"123"}&apiKey=*** (конечно дб, цв и ключ API определены). Ввод этого URI в браузере возвращает документ, который я ищу.

Android:

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") или используйте конструктор запросов и метод appendQueryParameter от android.net.Uri.Builder.

+0

Спасибо, что работает! – itaied

Смежные вопросы