Skip to content

Instantly share code, notes, and snippets.

@renatoathaydes
Created January 14, 2018 17:32
Show Gist options
  • Save renatoathaydes/242484f50456dcd6a5466d771225e62c to your computer and use it in GitHub Desktop.
Save renatoathaydes/242484f50456dcd6a5466d771225e62c to your computer and use it in GitHub Desktop.
HTTPComponents HTTPClient evolution
/*
* HTTPClient usage circa version 5.0-beta.
*/
package org.apache.hc.core5.http.examples;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpConnection;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.config.SocketConfig;
import org.apache.hc.core5.http.impl.Http1StreamListener;
import org.apache.hc.core5.http.impl.bootstrap.HttpRequester;
import org.apache.hc.core5.http.impl.bootstrap.RequesterBootstrap;
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.apache.hc.core5.http.message.RequestLine;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.http.protocol.HttpCoreContext;
import org.apache.hc.core5.util.Timeout;
/**
* Example of POST requests execution using classic I/O.
*/
public class ClassicPostExecutionExample {
public static void main(String[] args) throws Exception {
HttpRequester httpRequester = RequesterBootstrap.bootstrap()
.setStreamListener(new Http1StreamListener() {
@Override
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
System.out.println(connection + " " + new RequestLine(request));
}
@Override
public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
System.out.println(connection + " " + new StatusLine(response));
}
@Override
public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
if (keepAlive) {
System.out.println(connection + " can be kept alive");
} else {
System.out.println(connection + " cannot be kept alive");
}
}
})
.create();
HttpCoreContext coreContext = HttpCoreContext.create();
HttpHost target = new HttpHost("httpbin.org");
HttpEntity[] requestBodies = {
new StringEntity(
"This is the first test request",
ContentType.create("text/plain", StandardCharsets.UTF_8)),
new ByteArrayEntity(
"This is the second test request".getBytes(StandardCharsets.UTF_8),
ContentType.APPLICATION_OCTET_STREAM),
new InputStreamEntity(
new ByteArrayInputStream(
"This is the third test request (will be chunked)"
.getBytes(StandardCharsets.UTF_8)),
ContentType.APPLICATION_OCTET_STREAM)
};
SocketConfig socketConfig = SocketConfig.custom()
.setSoTimeout(5, TimeUnit.SECONDS)
.build();
String requestUri = "/post";
for (int i = 0; i < requestBodies.length; i++) {
ClassicHttpRequest request = new BasicClassicHttpRequest("POST", target,requestUri);
request.setEntity(requestBodies[i]);
try (ClassicHttpResponse response = httpRequester.execute(target, request, Timeout.ofSeconds(5), coreContext)) {
System.out.println(requestUri + "->" + response.getCode());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
}
}
}
}
/*
* HTTPClient usage circa version 4.4.
*/
import java.io.ByteArrayInputStream;
import java.net.Socket;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultBHttpClientConnection;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
/**
* Elemental example for executing multiple POST requests sequentially.
*/
public class ElementalHttpPost {
public static void main(String[] args) throws Exception {
HttpProcessor httpproc = HttpProcessorBuilder.create()
.add(new RequestContent())
.add(new RequestTargetHost())
.add(new RequestConnControl())
.add(new RequestUserAgent("Test/1.1"))
.add(new RequestExpectContinue(true)).build();
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpCoreContext coreContext = HttpCoreContext.create();
HttpHost host = new HttpHost("localhost", 8080);
coreContext.setTargetHost(host);
DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;
try {
HttpEntity[] requestBodies = {
new StringEntity(
"This is the first test request",
ContentType.create("text/plain", Consts.UTF_8)),
new ByteArrayEntity(
"This is the second test request".getBytes(Consts.UTF_8),
ContentType.APPLICATION_OCTET_STREAM),
new InputStreamEntity(
new ByteArrayInputStream(
"This is the third test request (will be chunked)"
.getBytes(Consts.UTF_8)),
ContentType.APPLICATION_OCTET_STREAM)
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket);
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/servlets-examples/servlet/RequestInfoExample");
request.setEntity(requestBodies[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
httpexecutor.preProcess(request, httpproc, coreContext);
HttpResponse response = httpexecutor.execute(request, conn, coreContext);
httpexecutor.postProcess(response, httpproc, coreContext);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, coreContext)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
import java.io.File;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
/**
* HTTPClient usage circa version 3.1.
*/
public class PostXML {
/**
*
* Usage:
* java PostXML http://mywebserver:80/ c:\foo.xml
*
* @param args command line arguments
* Argument 0 is a URL to a web server
* Argument 1 is a local filename
*
*/
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Usage: java -classpath <classpath> [-Dorg.apache.commons.logging.simplelog.defaultlog=<loglevel>] PostXML <url> <filename>]");
System.out.println("<classpath> - must contain the commons-httpclient.jar and commons-logging.jar");
System.out.println("<loglevel> - one of error, warn, info, debug, trace");
System.out.println("<url> - the URL to post the file to");
System.out.println("<filename> - file to post to the URL");
System.out.println();
System.exit(1);
}
// Get target URL
String strURL = args[0];
// Get file to be posted
String strXMLFilename = args[1];
File input = new File(strXMLFilename);
// Prepare HTTP post
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
post.setRequestEntity(entity);
// Get HTTP client
HttpClient httpclient = new HttpClient();
// Execute request
try {
int result = httpclient.executeMethod(post);
// Display status code
System.out.println("Response status code: " + result);
// Display response
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment