Okhttp PUT 请求到 nginx 服务器 NOT ALLOWED

Okhttp PUT request to nginx server NOT ALLOWED

更新:

curl -i -H "Accept: application/json" -H "token: token" -X PUT -d '{ "uid": 123, "name": "Name",                         }' http://api.myserver.com

HTTP/1.1 405 Not Allowed Server: nginx/1.4.6 (Ubuntu) Content-Type: application/json Transfer-Encoding: chunked Connection: keep-alive X-Powered-By: PHP/5.5.9-1ubuntu4.11 Cache-Control: no-cache Date: Thu, 25 Aug 2016 21:37:02 GMT

经过一番搜索我找到了原因:

  • 你需要用HttpDavModule编译nginx Whosebug.

  • 但我可以通过添加 "_METHOD=PUT","PUT" 从客户端解决我的问题 到我的 json.

  • 并将PUT请求转换为POST

  • 页眉("X-HTTP-Method-Override", "PUT").

    String json = "{ \"_METHOD=PUT\":\"PUT\",\"key\": \"value\"\" }";
    
    
    client.newCall(new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(JSON, json))
                    .Header("X-HTTP-Method-Override", "PUT")
                    .build()
            ).execute();
    

更新

  • 不需要在 body 上添加“_METHOD=PUT”,"PUT" 到 json。
  • 只需将 PUT 请求转换为 POST 并添加 Header("X-HTTP-Method-Override", "PUT") 即可。

    curl -i -H "Accept: application/json" -H "-HTTP-Method-Override: PUT" -H "token: token" -X POST -d '{ "uid": 123, "name": "Name"}' http://api.myserver.com
    

HTTP/1.1 200 OK Server: nginx/1.4.6 (Ubuntu) Content-Type: application/json Transfer-Encoding: chunked Connection: keep-alive X-Powered-By: PHP/5.5.9-1ubuntu4.11 Cache-Control: no-cache Date: Thu, 25 Aug 2016 21:37:02 GMT