在Java中使用JSON的HTTP POST
我想在Java中使用JSON进行简单的HTTP POST。
假设网址是www.site.com
并且它取值为{"name":"myname","age":"20"}
,例如标记为'details'
。
我将如何去创建POST的语法?
我似乎也无法在JSON Javadoc中找到POST方法。
这是你需要做的事情:
代码大致看起来像(你仍然需要调试它并使其工作)
//Deprecated
//HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params =new StringEntity("details={"name":"myname","age":"20"} ");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//handle response here...
}catch (Exception ex) {
//handle exception here
} finally {
//Deprecated
//httpClient.getConnectionManager().shutdown();
}
您可以使用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;
@ momo对Apache HttpClient 4.3.1或更高版本的回答。 我使用JSON-Java
来构建我的JSON对象:
JSONObject json = new JSONObject();
json.put("someKey", "someValue");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.close();
}
链接地址: http://www.djcxy.com/p/45857.html