HTTP POST using JSON in Java

前端 未结 11 990
南笙
南笙 2020-11-22 07:24

I would like to make a simple HTTP POST using JSON in Java.

Let\'s say the URL is www.site.com

and it takes in the value {\"name\":\"mynam

相关标签:
11条回答
  • 2020-11-22 08:09

    @momo's answer for Apache HttpClient, version 4.3.1 or later. I'm using JSON-Java to build my JSON object:

    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();
    }
    
    0 讨论(0)
  • 2020-11-22 08:10

    For Java 11 you can use new HTTP client:

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

    You can use publisher from InputStream, String, File. Converting JSON to the String or IS you can with Jackson.

    0 讨论(0)
  • 2020-11-22 08:13

    Here is what you need to do:

    1. Get the Apache HttpClient, this would enable you to make the required request
    2. Create an HttpPost request with it and add the header application/x-www-form-urlencoded
    3. Create a StringEntity that you will pass JSON to it
    4. Execute the call

    The code roughly looks like (you will still need to debug it and make it work):

    // @Deprecated HttpClient httpClient = new DefaultHttpClient();
    HttpClient httpClient = HttpClientBuilder.create().build();
    try {
        HttpPost request = new HttpPost("http://yoururl");
        StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
    } catch (Exception ex) {
    } finally {
        // @Deprecated httpClient.getConnectionManager().shutdown(); 
    }
    
    0 讨论(0)
  • 2020-11-22 08:19

    I recomend http-request built on apache http api.

    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. 
    }
    

    If you want send JSON as request body you can:

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

    I higly recomend read documentation before use.

    0 讨论(0)
  • 2020-11-22 08:20
    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();
    }
    
    0 讨论(0)
提交回复
热议问题