HttpUrlConnection PATCH request using Java

2019-08-02 05:41发布

I am trying to do a http PATCH request but I always get the 404 error, so maybe the settings of my connection are not correct:

        URL url = new URL("MyPath");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestMethod("POST");

        JsonObject jo = createMyJson();
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(jo.toString());
        out.close();

        System.out.println(conn.getResponseCode());
        System.out.println(conn.getResponseMessage());

I get the 404 error, Not found. When doing the same request using Postman, this is working.. Thank you for your help.

1条回答
ら.Afraid
2楼-- · 2019-08-02 06:30

Not all servers support X-HTTP-Method-Override. In that case your last resort is (if you are not using a decent HTTP client) to hack the URLConnection object.

I posted a complete solution here on SO, check it out.

查看更多
登录 后发表回答