Search code examples
javajsonhttpapache-httpclient-4.xoctoprint

How to send a POST Request to Octoprint in Java?


I want to send a POST Request to the Octoprint API via the Apache HttpClient, something like shown here: http://docs.octoprint.org/en/master/api/job.html#issue-a-job-command (e.g. to start a job). I've read the docs of both, but still getting "Bad Request" as answer.

Tried several other Post Request, but never getting something else. Guess I'm writing the request wrong somehow.

CloseableHttpClient posterClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://localhost:5000/api/job");
        post.setHeader("Host", "http://localhost:5000");
        post.setHeader("Content-type", "application/json");

        post.setHeader("X-Api-Key", "020368233D624EEE8029991AE80A729B");

        List<NameValuePair> content = new ArrayList<NameValuePair>();
        content.add(new BasicNameValuePair("command", "start"));



        post.setEntity(new UrlEncodedFormEntity(content));
        CloseableHttpResponse answer = posterClient.execute(post);

        System.out.println(answer.getStatusLine());

Solution

  • Likely the content type is wrong. As per documentation here, expect bodies to be in JSON formart. Your code on the other hand uses application/x-www-form-urlencoded as per this piece of code post.setEntity(new UrlEncodedFormEntity(content));

    Quick fix, make the below changes and try it out:

        String json= "{\"command\":\"start\"}";
        
        //This will change change you BasicNameValuePair to an Entity with the correct Content Type
        StringEntity entity = new StringEntity(json,ContentType.APPLICATION_JSON);
        //Now you just set it to the body of your post
        post.setEntity(entity);
    

    You will likely want to review how you create the content of your post. The above is just so you check if the issue is indeed related to the content type.

    Let us know of the outcome.