【发布时间】:2017-11-28 20:11:12
【问题描述】:
我有一些具有以下格式的字符串的 Java 代码:
{username=username, password=password}
我想将其转换为 JSON 并以可接受的格式将其传递给 Http Post 实体。我该怎么做?
预期:
{
"username": "username",
"password": "password"
}
代码sn-p:
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(
"https://url/api/v1/chk");
StringEntity input = new StringEntity(request.getBody().toString()); // I am sending an aplication/json content type JSON to the API that is invoking the https://url/api/v1/chk API input.setContentType("application/json");
postRequest.setEntity(input);HttpResponse response = httpClient.execute(postRequest); // This throws 400 bad request
【问题讨论】:
-
这听起来像是一个 XY 问题。该字符串首先来自哪里?我的猜测是你在一个对象上调用 toString(),然后你试图将该字符串转换为 JSON,而不是简单地将对象编组为 JSON。
-
@JBNizet-你是对的。我从 request.getBody() 获取对象。您能给我一个工作示例,说明如何将其作为应用程序/json 内容发送到 HTTP Post 实体。
-
有几十个 JSON 解析器/编组器和 HTTP 客户端。这完全取决于您使用的是什么。
-
@JBNizet - 我正在使用 HTTPClientBuilder 创建我的客户端来调用 API。我已经编辑了我的问题以提供有关代码 sn-p 的更多详细信息