如何在android中使用put方法向HTTPBody添加数据

时间:2016-12-06 09:00:38

标签: android json web-services httprequest http-put

我正在构建一个使用优步API乘坐请求端点的Android应用程序。我在HTTPBody中附加数据时出现问题,并且显示错误,例如不支持端点。

这些是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"}'

代码:

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

1 个答案:

答案 0 :(得分:1)

首先,您希望PUT正文属于application/json类型,但您要将httpPut对象的实体设置为UrlEncodedFormEntity 所以你需要先解决这个问题。 首先,您需要创建StringEntity对象,并将其contentType属性设置为application/json

在你的情况下,因为你的json字符串将是{"status":"accepted"},你需要实例化StringEntity类,如此

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

然后像这样设置内容类型

input.setContentType("application/json");

然后将httpput实体属性设置为我们刚刚创建的输入enity:

httpput.setEntity(input);

它只是替换

httpput.setEntity(new UrlEncodedFormEntity(params));

前两行

所以你的代码看起来像这样

<强>代码:

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

如果你想把它带到下一步,那么你需要在java概念中加强Json序列化和反序列化,并学习如何从Java对象生成json字符串,然后你可以将Java对象序列化为json字符串并实例化带有生成的json字符串的StringEntity