2016-12-06 3 views
2

Je construis une application Android qui utilise le point de terminaison de demande Uber API.J'ai du mal à ajouter des données dans HTTPBody et il montre une erreur comme les points de terminaison ne sont pas pris en charge.Comment ajouter des données à HTTPBody avec la méthode put dans android

Ce sont commande curl:

curl -X PUT 'https://sandbox-api.uber.com/v1/sandbox/requests/{REQUEST_ID}' 
\ -H 'Content-Type: application/json' 
\ -H 'Authorization: Bearer ' 
\ -d '{"status":"accepted"}' 

code:

public JSONObject getStatus(String address, String requestId, String product_id, float start_latitude, float start_longitude, float end_latitude, float end_longitude, String token) { 
     try { 

      httpClient = new DefaultHttpClient(); 
      httpput = new HttpPut("https://sandbox-api.uber.com/v1/requests/"+requestId); 
      **params.add(new BasicNameValuePair("status", "accepted"));** 

      httpput.setHeader("Authorization","Bearer "+token); 
      httpput.setHeader("Content-type", "application/json"); 
      httpput.setEntity(new UrlEncodedFormEntity(params)); 
      HttpResponse httpResponse = httpClient.execute(httpput); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "n"); 
      } 
      is.close(); 

      json = sb.toString(); 
      Log.e("JSONStr", json); 
     } catch (Exception e) { 
      e.getMessage(); 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     return jObj; 
    } 
+0

Comment le serveur attend-il le corps PUT? JSON? xml? encodé en url? – Bhargav

+0

il nécessite le format json –

+0

en fait je ne comprends pas comment ajouter le statut dans HTTPbody –

Répondre

1

D'abord, vous voulez corps PUT être de type application/json mais vous configurez l'entité de l'objet httpPut-UrlEncodedFormEntity Vous besoin d'abord résoudre ce problème. Tout d'abord, vous devez créer StringEntity objet, et définir sa contentType propriété à application/json

Dans votre cas puisque votre chaîne JSON va être {"status":"accepted"} vous devez instancier la classe comme StringEntity si

StringEntity input = new StringEntity("{\"status\":\"accepted\"}"); 

Et puis définir le type de contenu comme si

input.setContentType("application/json"); 

Réglez ensuite la propriété de l'entité httpput à la enity d'entrée que nous venons de créer comme ceci:

httpput.setEntity(input); 

C'est il suffit de remplacer

httpput.setEntity(new UrlEncodedFormEntity(params)); 

avec les 2 premières lignes

donc votre code ressemblera à ceci

code:

public JSONObject getStatus(String address, String requestId, String product_id, float start_latitude, float start_longitude, float end_latitude, float end_longitude, String token) { 
    try { 

     httpClient = new DefaultHttpClient(); 
     httpput = new HttpPut("https://sandbox-api.uber.com/v1/requests/"+requestId); 
     httpput.setHeader("Authorization","Bearer "+token); 
     httpput.setHeader("Content-type", "application/json"); 
     // Create the string entity 
     StringEntity input = new StringEntity("{\"status\":\"accepted\"}"); 
     // set the content type to json 
     input.setContentType("application/json"); 
     // set the entity property of the httpput 
     // request to the created input. 
     httpput.setEntity(input); 
     HttpResponse httpResponse = httpClient.execute(httpput); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "n"); 
     } 
     is.close(); 

     json = sb.toString(); 
     Log.e("JSONStr", json); 
    } catch (Exception e) { 
     e.getMessage(); 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    return jObj; 
} 

Si vous voulez passer à l'étape suivante, vous devez accélérer la sérialisation et la désérialisation de JSON dans les concepts Java et apprendre comment générer des chaînes JSON à partir d'objets Java, puis sérialiser les objets Java dans des chaînes JSON et instancier le StringEntity avec la chaîne JSON générée.

+0

alors aussi j'obtiens une erreur comme {"message": "Méthode non supportée pour ce point de terminaison.", "Code": "method_not_allowed"} et j'ai fait changements dans le code ci-dessus selon les suggestions, StringEntity input = new StringEntity ("{\" status \ ": \" accepté \ "}"); input.setContentType ("application/json"); httpput.setEntity (entrée); –

+0

@RohanChavan Eh bien, cela signifie que HttpPut n'est pas autorisé essayer HttpPost à la place – Bhargav

+0

Merci son travail –