我试图用这样的正文发送POST
请求
{
"method": "getAreas",
"methodProperties": {
"prop1" : "value1",
"prop2" : "value2",
}
}
这是我的代码
static final String HOST = "https://somehost.com";
public String sendPost(String method,
Map<String, String> methodProperties) throws ClientProtocolException, IOException {
HttpPost post = new HttpPost(HOST);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("method", method));
List<NameValuePair> methodPropertiesList = methodProperties.entrySet().stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
// ??? urlParameters.add(new BasicNameValuePair("methodProperties", methodPropertiesList));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
return EntityUtils.toString(response.getEntity());
}
}
但是BasicNameValuePair
的构造函数适用(String, String)
。所以我需要另一堂课。
有没有办法将methodPropertiesList
添加到urlParameters
?
class pojo1{
String method;
Map<String,String> methodProperties;
}
String postUrl = "www.site.com";// put in your url
Gson gson = new Gson();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson() converts your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
static final String HOST = "https://somehost.com";
public String sendPost(String method,
Map<String, String> methodProperties) throws ClientProtocolException, IOException {
HttpPost post = new HttpPost(HOST);
MyResource resource = new MyResource();
resource.setMethod(method);
MyNestedResource nestedResource = new MyNestedResource();
nestedResource.setMethodProperties(methodProperties);
resource.setNestedResourceMethodProperties(nestedResource);
post.setEntity(resource);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
return EntityUtils.toString(response.getEntity());
}
}
并且通常这就是您使用嵌套结构处理更复杂的json对象的方式。您必须为要发送的资源创建类(在您的示例中,它可能是一个类,并且在其中使用了map,但是如果嵌套对象具有特定的结构,通常也为嵌套对象创建一个类)。为了更好地了解整个图片,请涵盖本教程:https://www.baeldung.com/jackson-mapping-dynamic-object