【问题标题】:Android do PATCH/PUT to serverAndroid 对服务器进行 PATCH/PUT
【发布时间】:2014-05-19 06:42:50
【问题描述】:

我遇到了这个问题,我需要将数据放入或修补到服务器。我知道如何做一个标准的帖子,但我怎么能做这个 PATCH 或 PUT 到服务器? 服务器的URL是PATCH to www.example.com/api/documents,参数是doc_id(integer)。

这是我目前拥有的

HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(url);

        httpPost.setHeader("content-type", "application/json");
        httpPost.setHeader("accept-charset", "utf8");

        try {
            HttpResponse response = httpClient.execute(httpPost);
            responseString = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            Log.e("Request exception:", "excpetion", e);
        }
        return responseString;

但是我认为这段代码是错误的:)

【问题讨论】:

  • 这是 http POST 而不是 PUT。
  • @VedPrakash 我知道 - 你能告诉我如何对服务器执行 PUT 或 PATCH 操作吗?

标签: java android androidhttpclient


【解决方案1】:

这是最常见的方式---

创建 jsonObj 并放置 json 值:

JSONObject jsonObj = new JSONObject();
jsonObj .put("doc_id", <put your value> + "");
String response = callPutService(source, password, callingAPI, jsonObj);

这是被调用的 callPutService:

public String callPutService(String userName, String password, 
String type, JSONObject jsonObject) {
        String line = null, jsonString = "";
        HttpResponse response = null;
        InputStream inputStream = null;

        try {
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.
                    setConnectionTimeout
                    (client.getParams(), 20000); // Timeout Limit

            HttpPut put = new HttpPut(WEBSERVICE + type);

            StringEntity se = new StringEntity(jsonObject.toString());
            se.setContentType("application/json;charset=UTF-8");

            put.setHeader("Authorization",
                    "basic " +  Base64.
                    encodeToString((userName + ":" + password).getBytes(), 
                    Base64.URL_SAFE | Base64.NO_WRAP));
            put.setEntity(se);
            response = client.execute(put);
            int responseCode = response.getStatusLine().getStatusCode();

            if(responseCode == 200){
                //do whatever
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonString;
    }

【讨论】:

  • 这行代码中的WEBSERVICE是什么意思HttpPut put = new HttpPut(WEBSERVICE + type);
  • 这是您的完整服务器网址。在你的情况下 - WEBSERVICE + type = www.example.com/api/documents 其中WEBSERVICE = www.example.comtype = /api/documents
  • 嗯,我遇到了一个错误,我们可以聊聊我遇到的错误吗?
  • 这里是我现在使用的代码——我犯了什么错误吗? pastebin.com/vMsAPZty
  • doc_id 放在哪里?你遇到了什么错误 ?首先你必须把你的 json 参数放到 jsonobject 中,然后调用上面的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-10
  • 2014-02-21
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 2019-10-31
相关资源
最近更新 更多