HTTP POST using JSON in Java
我想在Java中使用JSON进行简单的HTTP POST。
假设网址为
例如,它采用标记为
我将如何为POST创建语法?
我似乎在JSON Javadocs中也找不到POST方法。
这是您需要做的:
代码大致看起来像(您仍然需要对其进行调试并使之正常工作)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //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类
按照上面的例子
1 | {"name":"myname","age":"20"} |
变成
一旦在pojo1类中设置了变量,就可以使用以下代码发送该变量
1 2 3 4 5 6 7 8 | 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); |
这些是进口
1 2 3 4 5 6 | 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
1 | import com.google.gson.Gson; |
@momo对于4.3.1或更高版本的Apache HttpClient的答案。我正在使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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(); } |
试试这个代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 Endpoints而言无效。
Google端点解决方案。
内容类型标头必须设置为" application / json"。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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:
1 2 3 4 | String payload ="{"name": "myname", "age": "20"}"; post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON)); response = client.execute(request); |
另外,您可以创建一个json对象,并像这样将字段放入对象
1 2 3 4 5 | HttpPost post = new HttpPost(URL); JSONObject payload = new JSONObject(); payload.put("name","myName"); payload.put("age","20"); post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON)); |
对于Java 11,您可以使用新的HTTP客户端:
1 2 3 4 5 6 7 8 9 10 11 12 | HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost/api")) .header("Content-Type","application/json") .POST(ofInputStream(() -> getClass().getResourceAsStream( "/some-data.json"))) .build(); client.sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println) .join(); |
您可以通过InputStream,String,File使用发布者。使用Jackson可以将JSON转换为String或IS。
Java 8与Apache httpClient 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("www.site.com"); String json ="details={"name":"myname","age":"20"}"; try { StringEntity entity = new StringEntity(json); httpPost.setEntity(entity); // set your POST request headers to accept json contents httpPost.setHeader("Accept","application/json"); httpPost.setHeader("Content-type","application/json"); try { // your closeablehttp response CloseableHttpResponse response = client.execute(httpPost); // print your status code from the response System.out.println(response.getStatusLine().getStatusCode()); // take the response body as a json formatted string String responseJSON = EntityUtils.toString(response.getEntity()); // convert/parse the json formatted string to a json object JSONObject jobj = new JSONObject(responseJSON); //print your response body that formatted into json System.out.println(jobj); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } |
我建议基于apache http api构建的http-request。
1 2 3 4 5 6 7 8 9 | 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. } |
如果要发送
1 | ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData); |
我强烈建议使用前阅读文档。