首页 > 解决方案 > android 应用中 PUT 请求的错误响应

问题描述

我正在开发一个应该向本地服务器发送PUT请求的 Android 应用程序,当我使用 curl 尝试相同的请求时,我得到了成功响应,但是从 Android 应用程序我得到了PUT请求错误,这是来自两者的请求移动应用程序和 curl,我使用 netcat 在我的 PC 上收听了这两个请求

user@Laptop:~$ nc -l 192.168.1.104 55555
PUT /api/relay/0 HTTP/1.1
Host: 192.168.1.104:55555
User-Agent: curl/7.58.0
Accept: application/json
Content-Length: 31
Content-Type: application/x-www-form-urlencoded

apikey=2E5DE48567FB10F2&value=1


user@Laptop:~$ nc -l 192.168.1.104 55555
PUT /api/relay/0 HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8
User-Agent: Dalvik/2.1.0 (Linux; U; Android 9; HRY-LX1MEB Build/HONORHRY-LX1MEB)
Host: 192.168.1.104:55555
Connection: Keep-Alive
Accept-Encoding: gzip
Content-Length: 31

apikey=2E5DE48567FB10F2&value=1

这是我的 android java 请求

public void jsonRequestVolley(int method, String url, String requestBody) {         
        RequestQueue queue = Volley.newRequestQueue(context); 

        JsonObjectRequest jsonRequest = new JsonObjectRequest(   
                method,                           
                url,                                            
                requestBody,
                successResponse(),  
                errorResponse()   
        )  
        {

            /**
             * Passing some request headers
             * */
            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json");
                return headers;
            }

        };

        queue.add(jsonRequest);
    }   

工作卷曲命令是

curl -X PUT -H "Accept: application/json" http://192.168.1.105:55555/api/relay/0 --data "apikey=2E5DE48567FB10F2&value=1"```

标签: javaandroidcurlputnetcat

解决方案


由于本地服务器的要求,我修复了标头,所以它现在看起来像

PUT /api/relay/0 HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
User-Agent: Dalvik/2.1.0 (Linux; U; Android 9; HRY-LX1MEB Build/HONORHRY-LX1MEB)
Host: 192.168.1.104:55555
Connection: Keep-Alive
Accept-Encoding: gzip
Content-Length: 31

我将以下内容添加到 Android 代码中

@Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<String, String>();

                headers.put("Accept", "application/json");
                return headers;
            }

@Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

全部在请求代码中。


推荐阅读