How do I write to an OutputStream using DefaultHttpClient?

后端 未结 4 1907
挽巷
挽巷 2020-12-09 05:10

How do I get an OutputStream using org.apache.http.impl.client.DefaultHttpClient?

I\'m looking to write a long string to an output stream.

4条回答
  •  悲哀的现实
    2020-12-09 06:09

    I wrote an inversion of Apache's HTTP Client API [PipedApacheClientOutputStream] which provides an OutputStream interface for HTTP POST using Apache Commons HTTP Client 4.3.4.

    Calling-code looks like this:

    // Calling-code manages thread-pool
    ExecutorService es = Executors.newCachedThreadPool(
      new ThreadFactoryBuilder()
      .setNameFormat("apache-client-executor-thread-%d")
      .build());
    
    
    // Build configuration
    PipedApacheClientOutputStreamConfig config = new      
      PipedApacheClientOutputStreamConfig();
    config.setUrl("http://localhost:3000");
    config.setPipeBufferSizeBytes(1024);
    config.setThreadPool(es);
    config.setHttpClient(HttpClientBuilder.create().build());
    
    // Instantiate OutputStream
    PipedApacheClientOutputStream os = new     
    PipedApacheClientOutputStream(config);
    
    // Write to OutputStream
    os.write(...);
    
    try {
      os.close();
    } catch (IOException e) {
      logger.error(e.getLocalizedMessage(), e);
    }
    
    // Do stuff with HTTP response
    ...
    
    // Close the HTTP response
    os.getResponse().close();
    
    // Finally, shut down thread pool
    // This must occur after retrieving response (after is) if interested   
    // in POST result
    es.shutdown();
    

    Note - In practice the same client, executor service, and config will likely be reused throughout the life of the application, so the outer prep and close code in the above example will likely live in bootstrap/init and finalization code rather than directly inline with the OutputStream instantiation.

提交回复
热议问题