在Java中使用JSON的HTTP POST


Answers

您可以使用Gson庫將您的Java類轉換為JSON對象。

根據上面的示例為要發送的變量創建pojo類

{"name":"myname","age":"20"}

class pojo1
{
   String name;
   String age;
   //generate setter and getters
}

一旦你在pojo1類中設置了變量,你可以使用下面的代碼發送它

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);

這些是進口產品

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

和GSON

import com.google.gson.Gson;
Question

我想在Java中使用JSON進行簡單的HTTP POST。

假設網址是www.site.com

並且它取值為{"name":"myname","age":"20"} ,例如標記為'details'

我將如何去創建POST的語法?

我似乎也無法在JSON Javadoc中找到POST方法。




試試這個代碼:

HttpClient httpClient = new DefaultHttpClient();

try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
    request.addHeader("content-type", "application/json");
    request.addHeader("Accept","application/json");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);

    // handle response here...
}catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.getConnectionManager().shutdown();
}



我推薦建立在apache http api上的http-request

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri, String.class)
    .responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();

public void send(){
   ResponseHandler<String> responseHandler = httpRequest.execute("details", yourJsonData);

   int statusCode = responseHandler.getStatusCode();
   String responseContent = responseHandler.orElse(null); // returns Content from response. If content isn't present returns null. 
}

如果你想發送JSON作為請求主體,你可以:

  ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);

在使用之前,我建議閱讀文檔。