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

How to add data to HTTPBody with put method in android

我正在构建一个使用 Uber API 乘车请求的 android 应用 endpoint.I 在 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;
    }

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

在你的情况下,因为你的 json 字符串将是 {"status":"accepted"} 你需要像这样实例化 StringEntity class

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

然后像这样设置内容类型

input.setContentType("application/json");

然后将 httpput 实体 属性 设置为我们刚刚创建的输入实体,如下所示:

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 序列化和反序列化,并学习如何从中生成 json 字符串Java 个对象,然后你可以将 Java 个对象序列化为 json 个字符串,并用生成的 json 个字符串实例化 StringEntity