我想用Java中的JSON创建一个简单的HTTP POST。
假设URL是www.site.com
例如,它接受标记为'details'
的值{"name":"myname","age":"20"}
。
我该如何创建帖子的语法呢?
我似乎在JSON Javadoc中也找不到POST方法。
发布于 2014-01-17 12:00:54
您可以使用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;
发布于 2013-11-12 02:02:59
@momo针对4.3.1或更高版本的Apache HttpClient的答案。我正在使用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();
}
发布于 2011-08-25 04:06:53
使用HttpURLConnection可能是最简单的。
http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
您将使用JSONObject或其他工具来构造您的JSON,但不是用来处理网络的;您需要序列化它,然后将它传递给HttpURLConnection进行POST。
https://stackoverflow.com/questions/7181534
复制相似问题