3 回答

TA貢獻1757條經驗 獲得超7個贊
您的請求看起來像 json 結構,因此發布如下數據:
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);

TA貢獻1744條經驗 獲得超4個贊
對于這個問題有一個眾所周知的方法。在大多數情況下,您將創建自己的對象來描述要在 HttpPost 中發送的內容。所以你會得到類似的東西:
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);
? ? StringEntity strEntity = new StringEntity(gson.toJson(resource));
? ? post.setEntity(strEntity);
? ? try (CloseableHttpClient httpClient = HttpClients.createDefault();
? ? ? ? CloseableHttpResponse response = httpClient.execute(post)) {
? ? ? return EntityUtils.toString(response.getEntity());
? ? }
? }
這通常是您使用嵌套結構處理更復雜的 json 對象的方式。您必須為要發送的資源創建類(在您的示例中,它可能是一個類并在其中使用映射,但通常您也為嵌套對象創建一個類,如果它具有特定的結構)。

TA貢獻1820條經驗 獲得超9個贊
static final String HOST = "https://somehost.com";
? public String sendPost(String method, Map<String, String> methodProperties) throws ClientProtocolException, IOException {
? ? HttpPost post = new HttpPost(HOST);??
? ? Gson gson = new Gson();
? ? Params params = new Params(method, methodProperties);
? ? StringEntity entity = new StringEntity(gson.toJson(params));? ?
? ? post.setEntity(entity);
? ? try (CloseableHttpClient httpClient = HttpClients.createDefault();
? ? ? ? CloseableHttpResponse response = httpClient.execute(post)) {
? ? ? return EntityUtils.toString(response.getEntity());
? ? }
? }
? class Params {
? ? String method;? ?
? ? Map<String, String> methodProperties;
? ? public Params(String method, Map<String, String> methodProperties) {
? ? ? this.method = method;
? ? ? this.methodProperties = methodProperties;
? ? }
? ? //getters
? }
添加回答
舉報