在Java中使用JSON的HTTP POST

我想在Java中使用JSON做一个简单的HTTP POST。

假设网址是www.site.com

并且它取值为{"name":"myname","age":"20"} ,例如标记为'details'

我将如何去创建POST的语法?

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

这是你需要做的:

  1. 获取Apache HttpClient,这将使您能够提出所需的请求
  2. 创建一个HttpPost请求,并添加标题“application / x-www-form-urlencoded”
  3. 创建一个你将传递JSON的StringEntity
  4. 执行呼叫

代码大致看起来像(你仍然需要调试它,并使其工作)

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

和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(); } 

这可能是最简单的使用HttpURLConnection 。

http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139

您将使用JSONObject或其他来构建您的JSON,但不处理网络; 你需要序列化它,然后将它传递给一个HttpURLConnection POST。

 protected void sendJson(final String play, final String prop) { Thread t = new Thread() { public void run() { Looper.prepare(); //For Preparing Message Pool for the childThread HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000); //Timeout Limit HttpResponse response; JSONObject json = new JSONObject(); try { HttpPost post = new HttpPost("http://192.168.0.44:80"); json.put("play", play); json.put("Properties", prop); StringEntity se = new StringEntity(json.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); response = client.execute(post); /*Checking response */ if (response != null) { InputStream in = response.getEntity().getContent(); //Get the data in the entity } } catch (Exception e) { e.printStackTrace(); showMessage("Error", "Cannot Estabilish Connection"); } Looper.loop(); //Loop in the message queue } }; t.start(); } 

试试这个代码:

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

我发现这个问题寻找解决方案,如何发送从Java客户端发送到Google端点的请求。 以上答案很可能是正确的,但对于Google Endpoint不起作用。

Google终端解决方案。

  1. 请求正文只能包含JSON字符串,而不能包含name = value对。
  2. 内容类型头必须设置为“application / json”。

     post("http://localhost:8888/_ah/api/langapi/v1/createLanguage", "{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}"); public static void post(String url, String param ) throws Exception{ String charset = "UTF-8"; URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); try (OutputStream output = connection.getOutputStream()) { output.write(param.getBytes(charset)); } InputStream response = connection.getInputStream(); } 

    当然也可以使用HttpClient完成。

我推荐建立在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); 

在使用之前,我建议阅读文档。