java Android Volley PUT 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26697122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:25:06  来源:igfitidea点击:

Android Volley PUT request

javaandroidrestandroid-volley

提问by HairyLemon

i'm new to Volley and Android in general. Below is code snippet (Android using Volley) which i'm trying to execute, however it's the server returns a 400. Using another REST Client works perfectly. It's a request to the server using PUT method.

我是 Volley 和 Android 的新手。下面是我正在尝试执行的代码片段(使用 Volley 的 Android),但是服务器返回 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);
}

When i execute this code i always get a 400 Bad request back and i can't figure out why. Using another client like Postman, it works as expected. Here is the postman request:

当我执行这段代码时,我总是收到一个 400 Bad 请求,我不知道为什么。使用像 Postman 这样的另一个客户端,它按预期工作。这是邮递员的请求:

Raw Request:
{ "token": "blah", "password": "ttttt", "username": "tester3" }

原始请求:
{“令牌”:“废话”,“密码”:“ttttt”,“用户名”:“tester3”}

Headers: Content-Type: application/json

I can't see anything wrong with the request i'm hoping someone can point out what i'm doing wrong?

我看不出请求有什么问题,我希望有人能指出我做错了什么?

回答by Siddarth G

Sometimes , adding header "Content-Type", "application/json" in getHeaders() will not work its better to also override getBodyContentType() and return the header here.

有时,在 getHeaders() 中添加标头“Content-Type”、“application/json”不会更好地覆盖 getBodyContentType() 并在此处返回标头。

So along with ,

所以随着,

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

also add,

还补充说,

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

This worked for me while using POST.

这在使用 POST 时对我有用。

回答by Andrea Motto

JsonObjectRequestadds Content-Type: application/json; charset=utf-8by default. Your headers.put("Content-Type", "application/json");adds another Content-Typeand some applications don't work with multiple Content-Typedefinitions. You should try to remove headers.put("Content-Type", "application/json");.

JsonObjectRequestContent-Type: application/json; charset=utf-8默认添加。您headers.put("Content-Type", "application/json");添加了另一个,Content-Type并且某些应用程序不适用于多个Content-Type定义。您应该尝试删除headers.put("Content-Type", "application/json");.

回答by jonathan3087

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

This worked for me using a PUT request.

这对我使用 PUT 请求有效。

回答by bayramcicek

I was looking for Android Volley Put (JSON) with request body in Kotlin language but all answers in Java. Maybe someone looking for answers in Kotlin so I created Put with request body in Kotlin language:

我正在寻找带有 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)
}

回答by László Csiki

Just try with a StringRequest, like this:

只需尝试使用 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);
        }

回答by rolandvitezhu

Some hosting service provider block certain request methods, such as PUT or DELETE - e.g. 000webhost blocks PUT and DELETE requests for free users. If PUT method is blocked on the host for some reason, you can substitute it with POST method. I know, this is not the best solution, but it works.

一些托管服务提供商会阻止某些请求方法,例如 PUT 或 DELETE - 例如000webhost 会阻止免费用户的 PUT 和 DELETE 请求。如果 PUT 方法由于某种原因在主机上被阻止,您可以将其替换为 POST 方法。我知道,这不是最好的解决方案,但它有效。

回答by Francisco Arriagada

I spent a lot of time looking for how to do this. What worked for me was changing

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

Request.Method.PUT

to

Request.Method.POST