0

Well, i have this request in Postman:

127.0.0.1:8000/empleado/615050/retrieve-update/

and i add this body:

{"nombre":Marc}

this request working for me, in my API development in Django

but, when i try to replicate this request in my Java desktop app, fail and nothing happen. This is my Java code:

public void sendJson() {

        JsonObjectBuilder o = Json.createObjectBuilder();
        o.add("contrasenia", txtPass.getText());
        JsonObject contra = o.build();
        String contraS = contra.toString();
        System.out.println(contraS);
        
        try {
            URL url = new URL("http://localhost:8000/empleado/" + txtUsuario.getText() + "/retrieve-update/");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("PATCH");
            conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            OutputStream os = conn.getOutputStream();
            os.write(contraS.getBytes(StandardCharsets.UTF_8));
            os.close();
   

        } catch (MalformedURLException malformedURLException) {
            malformedURLException.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

Ideas? thank, sorry for my English

Diego K.
  • 27
  • 4
  • The `JSON`-object you posted is not a valid `JSON`-object, `Marc` must be surrounded by `"`. – Turing85 Apr 22 '21 at 20:58
  • In development it can be useful to have an error catch-all like `catch (Exception e)` so you can print out if an unknown one occurs. – Chris Gilardi Apr 22 '21 at 21:01

1 Answers1

2

This is because, unfortunately, PATCH is not a legal verb for HttpURLConnection

See the Javadoc for HttpURLConnection#setRequestMethod

Set the method for the URL request, one of:
GET
POST
HEAD
OPTIONS
PUT
DELETE
TRACE
are legal, subject to protocol restrictions. The default method is GET.

There are workarounds like here but your server should be compatible with the custom header.

I'd probably try to use a more advanced HTTP client if I were you

Or any other

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89