我想通过Apache HttpClient向Octoprint发送一个POST请求,如下所示:http://docs.octoprint.org/en/master/api/job.html#issue-a-job-command (例如,启动作业)。我已经阅读了这两种方法的文档,但仍然得到了“不良请求”作为回答。
尝试了其他几个邮政请求,但从来没有得到其他东西。我想我写错了请求。
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());发布于 2019-07-25 17:56:57
内容类型可能是错误的。根据文档这里,期望身体在JSON中。另一方面,根据这段代码post.setEntity(new UrlEncodedFormEntity(content));,您的代码使用了application/x-www-form-urlencoded。
快速修复,进行以下更改并尝试它:
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);您可能想回顾一下如何创建文章的内容。以上只是检查问题是否确实与内容类型有关。
让我们知道结果。
https://stackoverflow.com/questions/57207309
复制相似问题