Run HTTP POST asynchronously JAVA



  • I have a method that sends a POST to the server, how can I send multiple requests asynchronously?

    public void sendPost (Object content) {     
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        URL url;
    
    try {
    
        String jsonInString = mapper.writeValueAsString(content);
    
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    
            HttpPost post = new HttpPost(URL_POST);
            StringEntity params = new StringEntity(jsonInString, "UTF-8");
            post.addHeader("content-type", "application/json");
            post.setEntity(params);
            CloseableHttpResponse response = httpClient.execute(post);
            String responseBody = EntityUtils.toString(response.getEntity());
     }
    

    }



  • Follow an example that might help you:

    public class PostRequest implements Callable<InputStream> {
    
    private String url;
    private String body;
    
    public PostRequest(String url, String body) {
        this.url = url;
        this.body = body;
    }
    
    @Override
    public InputStream call() throws Exception {
    
        URL myurl = new URL(url);
        HttpURLConnection con = (HttpURLConnection) myurl.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Java client");
        con.setDoOutput(true);
    
        try( DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
           wr.writeBytes(body);
        }
    
        return con.getInputStream();
    }
    

    }

    public class Main {

    public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        Future&lt;InputStream&gt; response1 = executor.submit(new PostRequest(**&lt;url&gt;**, **&lt;content&gt;**));
        Future&lt;InputStream&gt; response2 = executor.submit(new PostRequest(**&lt;url&gt;**, **&lt;content&gt;**));
    
        ByteArrayOutputStream totalResponse = new ByteArrayOutputStream();
    
        IOUtils.copy(response1.get(), totalResponse);
        response1.get().close();
        IOUtils.copy(response2.get(), totalResponse);
        response2.get().close();
    
        executor.shutdown();
    
        System.out.println(totalResponse.toString());
    }
    

    }


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 3
  • 2
  • 2
  • 1
  • 2
  • 2
  • 2