首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何向Java中的Octoprint发送POST请求?

如何向Java中的Octoprint发送POST请求?
EN

Stack Overflow用户
提问于 2019-07-25 17:26:55
回答 1查看 216关注 0票数 1

我想通过Apache HttpClient向Octoprint发送一个POST请求,如下所示:http://docs.octoprint.org/en/master/api/job.html#issue-a-job-command (例如,启动作业)。我已经阅读了这两种方法的文档,但仍然得到了“不良请求”作为回答。

尝试了其他几个邮政请求,但从来没有得到其他东西。我想我写错了请求。

代码语言:javascript
复制
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());
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-25 17:56:57

内容类型可能是错误的。根据文档这里,期望身体在JSON中。另一方面,根据这段代码post.setEntity(new UrlEncodedFormEntity(content));,您的代码使用了application/x-www-form-urlencoded。

快速修复,进行以下更改并尝试它:

代码语言:javascript
复制
    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);

您可能想回顾一下如何创建文章的内容。以上只是检查问题是否确实与内容类型有关。

让我们知道结果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57207309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档