HttpUrlConnection PATCH request using Java

2019-08-02 06:00发布

问题:

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:

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.