Android Volley PUT请求

时间:2014-11-02 07:45:04

标签: java android rest android-volley

我是Volley和Android的新手。下面是我试图执行的代码片段(Android使用Volley),但是服务器返回400.使用另一个REST客户端可以完美地工作。它是使用PUT方法向服务器发出的请求。

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    sendRequest();
}

private void sendRequest() {
    RequestQueue queue = Volley.newRequestQueue(this);

    final JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("password", "ttttt");
        jsonObject.put("username", "tester3");
        jsonObject.put("token", "blah");
    } catch (JSONException e) {
        // handle exception
    }


    JsonObjectRequest putRequest = new JsonObjectRequest(Request.Method.PUT, url, jsonObject,
            new Response.Listener<JSONObject>()
            {
                @Override
                public void onResponse(JSONObject response) {
                    // response
                    Log.d("Response", response.toString());
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    Log.d("Error.Response", error.toString());
                }
            }
    ) {

        @Override
        public Map<String, String> getHeaders()
        {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");
            return headers;
        }

        @Override
        public byte[] getBody() {

            try {
                Log.i("json", jsonObject.toString());
                return jsonObject.toString().getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return null;
        }
    };

    queue.add(putRequest);
}

当我执行此代码时,我总是得到400 Bad请求,我无法弄清楚原因。 使用像Postman这样的其他客户端,它按预期工作。这是邮递员的要求:

原始请求:
    {     &#34;令牌&#34;:&#34; blah&#34;,     &#34;密码&#34;:&#34; ttttt&#34;,     &#34;用户名&#34;:&#34; tester3&#34;     }

Headers: Content-Type: application/json

我无法看到该请求有任何问题我希望有人可以指出我做错了什么?

7 个答案:

答案 0 :(得分:4)

有时,在getHeaders()中添加标题“Content-Type”,“application / json”将无法更好地覆盖getBodyContentType()并在此返回标题。

所以一起,

public Map<String, String> getHeaders()
    {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json"); 
        return headers;
    }

还添加,

    @Override
    public String getBodyContentType() {
        return "application/json";
    }

这在使用POST时对我有用。

答案 1 :(得分:2)

JsonObjectRequest默认添加Content-Type: application/json; charset=utf-8。您的headers.put("Content-Type", "application/json");会添加另一个Content-Type,而某些应用程序无法使用多个Content-Type定义。您应该尝试删除headers.put("Content-Type", "application/json");

答案 2 :(得分:2)

我一直在寻找带有Kotlin语言的请求正文的Android Volley Put(JSON),但所有答案都使用Java。也许有人在Kotlin中寻找答案,所以我用Kotlin语言创建了带有请求正文的Put:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // let's say we have token, apiLink, val1, val2, val3 as a String
    // created a function sendPutRequest()
    sendPutRequest(token, apiLink, val1, val2, val3)
}

private fun sendPutRequest(
    token: String,
    apiLink: String,
    val1: String,
    val2: String,
    val3: String
) {

    val queue = Volley.newRequestQueue(this)
    val jsonObject = JSONObject()

    try {
        jsonObject.put("token", token)
        jsonObject.put("val1", val1)
        jsonObject.put("val2", val2)
        jsonObject.put("val3", val3)
    } catch (e: JSONException) {
        // handle exception
        Log.i("json_error: ", "$e")
    }

     val putRequest: JsonObjectRequest =
        object : JsonObjectRequest(
            Method.PUT, apiLink, jsonObject,
            Response.Listener { response ->
                // response
                Log.i("response: ", "$response")
            },
            Response.ErrorListener { error ->
                // error
                Log.i("error: ", "$error")
            }
        ) {

            override fun getHeaders(): Map<String, String> {
                val headers: MutableMap<String, String> =
                    HashMap()
                headers["Content-Type"] = "application/json"
                headers["Accept"] = "application/json"
                return headers
            }

            override fun getBody(): ByteArray {
                    Log.i("json", jsonObject.toString())
                    return jsonObject.toString().toByteArray(charset("UTF-8"))
            }

        }
    queue.add(putRequest)
}

答案 3 :(得分:0)

尝试使用StringRequest,如下所示:

StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
        new Response.Listener<String>()
        {
@Override
public void onResponse(String response) {
        // response
        Log.d("Response", response.toString());
        }
        },
        new Response.ErrorListener()
        {
@Override
public void onErrorResponse(VolleyError error) {
        // error
        Log.d("Error.Response", error.toString());
        }
        }
        ) {

@Override
public Map<String, String> getHeaders()
        {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        //or try with this:
        //headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        return headers;
        }
@Override
protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("password", "ttttt");
        params.put("username", "tester3");
        params.put("token", "blah");
        return params;
        }
        };

        queue.add(putRequest);
        }

答案 4 :(得分:0)

 @Override
public String getBodyContentType() {
    return "application/json";
}

这对我使用PUT请求很有用。

答案 5 :(得分:-1)

某些托管服务提供商阻止某些请求方法,例如PUT或DELETE-例如000webhost blocks PUT and DELETE requests for free users。如果由于某种原因在主机上阻止了PUT方法,则可以将其替换为POST方法。我知道,这不是最好的解决方案,但是可以。

答案 6 :(得分:-5)

我花了很多时间寻找如何做到这一点。对我有用的是改变

var files=$('#ElementID').files;
 for (i=0;i<files.length;i++){
     $("#gridview2").append("<tr><td>" +files[i].fileName + 
                           "</td><td>" + files[i].fileSize + "</td></tr>");
  }

Request.Method.PUT