Search code examples
androidjsonweb-serviceshttprequesthttp-put

How to add data to HTTPBody with put method in android


I am building an android app that uses the Uber API ride request endpoint.I am having trouble regarding appending data in HTTPBody and it is showing error like endpoints are not supported.

These are curl command:

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;
    }

Solution

  • First you want to the PUT body to be of type application/json but you are setting the httpPut object's entity to UrlEncodedFormEntity So you need to first fix this. First you need to create StringEntity object, and set its contentType property to application/json

    In your case since your json string is going to be {"status":"accepted"} you need to instantiate the StringEntity class like so

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

    And then set the content type like so

    input.setContentType("application/json");
    

    Then set the httpput entity property to the input enity we just created like so:

    httpput.setEntity(input);
    

    That's it just replace

    httpput.setEntity(new UrlEncodedFormEntity(params));
    

    with the first 2 lines

    So your code will look like this

    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;
    }
    

    if you want to take this to the next step, then you need to ramp up on Json serialization and deserialization in java concepts and learn how to generate json strings from Java objects, then you can serialize Java objects to json strings and instantiate the StringEntity with the generated json string.