【问题标题】:How to add data to HTTPBody with put method in android如何在 android 中使用 put 方法将数据添加到 HTTPBody
【发布时间】:2016-12-06 09:00:37
【问题描述】:

我正在构建一个使用 Uber 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;
    }

【问题讨论】:

  • 服务器如何期待 PUT 正文? json? xml? url 编码?
  • 需要json格式
  • 实际上我没有得到如何在 HTTPbody 中附加状态
  • 你用的是哪个http库?
  • org.apache.httpcomponents:httpclient:4.5 我正在使用的这些依赖项

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


【解决方案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 实体属性设置为我们刚刚创建的输入实体,如下所示:

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字符串并实例化StringEntity 与生成的 json 字符串。

【讨论】:

  • 然后我也收到类似 {"message":"Method not supported for this endpoint.","code":"method_not_allowed"} 之类的错误,并且我已按照您的建议对上述代码进行了更改, StringEntity 输入 = new StringEntity("{\"status\":\"accepted\"}"); input.setContentType("应用程序/json"); httpput.setEntity(输入);
  • @RohanChavan 那么这意味着不允许 HttpPut 尝试 HttpPost 代替
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多