Search code examples
javaandroidhttpurlconnectionput

PUT request (JAVA) with HttpUrlConnection


I'm trying to do a "PUT" request with Android Studio. But, actually, it doesn't work, I received a "404 not found" whereas I got all the needed infos.


String url = "https://[...]";

        URL obj = null;
        try {
            obj = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }


        HttpURLConnection con = null;
        DataOutputStream dataOutputStream = null;
        try {
            con = (HttpURLConnection) obj.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // optional default is GET
        try {
            con.setRequestMethod("PUT");
            con.setDoInput(true);
            con.setDoOutput(true);
            System.out.println("Info User to update : " + params[0]);

            con.setRequestProperty("X-Auth-Token", params[0].get("token"));
            [...]

            con.setRequestProperty("shop_id", params[1].get("id"));

            dataOutputStream = new DataOutputStream(con.getOutputStream());
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
            osw.flush();
            osw.close();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (dataOutputStream != null) {
                try {
                    dataOutputStream.flush();
                    dataOutputStream.close();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }

        int responseCode = 0;
        try {
            responseCode = con.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
        }

If I try the request on Symfony (web app), it's worked well, but with the code, not anymore... Do you see any problems with my request ?


Solution

  • Problem solved, I was able to do what I wanted using a PATCH request instead.