2013-09-19 7 views
0

Мое приложение падает на «((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),"UTF-8"));» и выдает исключение «java.lang.ClassCastException:org.apache.http.client.methods.HttpGet».Приложение падает на httGet при попытке отправить Json?

JSONObject jo = new JSONObject(); 
    try { 
     jo.put("devicetoken", devicetoken); 
     URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com", 
       "/rest/list/myprayerlist/"+Helper.email, null, null); 

     HttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(uri); 

     // Prepare JSON to send by setting the entity 
     ((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(), 
       "UTF-8")); 

     // Set up the header types needed to properly transfer JSON 
     httpGet.setHeader("Content-Type", "application/json"); 
     httpGet.setHeader("Accept-Encoding", "application/json"); 
     httpGet.setHeader("Accept-Language", "en-US"); 

     // Execute POST 
     response = httpClient.execute(httpGet); 
     String string_response = EntityUtils.toString(response.getEntity()); 
     string_resp = string_response += ""; 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
    save(string_resp); 
    return result; 
+1

почему вы повторно Отдавая свой HttpGet объект HTTPResponse? – Ritaban

+1

Вы не можете наложить 'HttpResponse' на' httpGet', попробуйте удалить приведение на httpGet – reidzeibel

+0

Это покажет мне ошибку «Метод setEntity (StringEntity) не определен для типа HttpGet« – aQ1711

ответ

0

Если вы хотите поместить некоторые данные для запроса тела, вы должны использовать HttpPost вместо HttpGet. HttpPost имеет функцию для этого: setEntity(HttpEntity entity)

. Пример:

JSONObject jo = new JSONObject(); 
try { 
    jo.put("devicetoken", devicetoken); 
    URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com", 
      "/rest/list/myprayerlist/"+Helper.email, null, null); 

    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(uri); 

    // Prepare JSON to send by setting the entity 
    httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8")); 

    // Set up the header types needed to properly transfer JSON 
    httpGet.setHeader("Content-Type", "application/json"); 
    httpGet.setHeader("Accept-Encoding", "application/json"); 
    httpGet.setHeader("Accept-Language", "en-US"); 

    // Execute POST 
    HttpResponse response = httpClient.execute(httpPost); 
    String string_response = EntityUtils.toString(response.getEntity()); 
    string_resp = string_response += ""; 
} catch (Exception ex) { 
    ex.printStackTrace(); 
} 
save(string_resp); 
return result; 
+0

Можете ли вы отправить функцию httpGet с помощью приведенного выше кода. Благодарю. – aQ1711

+0

Обновленный ответ с примером –

0

активность { OnCreate { новый HitService() выполнить (addparams здесь); }}

защищенные строки doInBackground (String ... PARAMS) {

   String result = null; 

       HttpClient httpClient = new DefaultHttpClient(); 
       HttpGet httpGet = new HttpGet("http://your url=" + params[0]); 


       HttpResponse response; 
       try { 
         response = httpClient.execute(httpGet);     
         result = EntityUtils.toString(response.getEntity());   

       } catch (ClientProtocolException e) { 

         e.printStackTrace(); 
       } catch (IOException e) { 

         e.printStackTrace(); 
       } 

       return result; 
     } 
+0

protected String doInBackground (String ... params) он должен вернуть HashMap. – aQ1711

+0

Да, он возвращает ответ в hashmap, чем мы можем легко разобрать его. – Dev

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