Dear Wiki user, You have subscribed to a wiki page or wiki category on "Httpcomponents Wiki" for change notification.
The following page has been changed by QuintinBeukes: http://wiki.apache.org/HttpComponents/GeneralHttpCoreIntroduction The comment on the change is: Added the source files ------------------------------------------------------------------------------ We will be calling the basic class org.apache.http.examples.SimpleHttpRequest. It will contain a main method to easily run and experiment with it. - <link to="src.zip">You can download the resulting classes here.</link> + The complete source code for the classes built in on this page are found at the end of this page. [#top See the table of contents above.] == Static Member Setup == For all requests there are some objects which are shared. These do not need @@ -618, +618 @@ Hope this guide was helpful. + = Source Code for Classes = + == SimpleHttpRequest.java == + {{{#!java numbers=off + package org.apache.http.example; + + import java.io.BufferedInputStream; + import java.io.IOException; + import java.io.InputStream; + import java.net.MalformedURLException; + import java.net.URL; + + import org.apache.http.Header; + import org.apache.http.HttpEntity; + import org.apache.http.HttpException; + import org.apache.http.HttpHost; + import org.apache.http.HttpRequest; + import org.apache.http.HttpResponse; + import org.apache.http.HttpVersion; + import org.apache.http.impl.DefaultHttpClientConnection; + import org.apache.http.message.BasicHttpRequest; + import org.apache.http.params.BasicHttpParams; + import org.apache.http.params.HttpParams; + import org.apache.http.params.HttpProtocolParams; + import org.apache.http.protocol.BasicHttpContext; + import org.apache.http.protocol.BasicHttpProcessor; + import org.apache.http.protocol.ExecutionContext; + import org.apache.http.protocol.HttpContext; + 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; + + + public class SimpleHttpRequest + { + private static final HttpParams params; + + private static final BasicHttpProcessor httpProcessor; + + private static final HttpRequestExecutor httpExecutor; + + private static final ConnectionManager connectionManager; + + private final HttpContext context = new BasicHttpContext(null); + + private final HttpRequest request; + + private final DefaultHttpClientConnection connection; + + private HttpResponse response; + + private InputStream inputStream; + + static + { + // parameters + params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, "UTF-8"); + HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); + HttpProtocolParams.setUseExpectContinue(params, true); + + // processors + httpProcessor = new BasicHttpProcessor(); + // Required protocol interceptors + httpProcessor.addInterceptor(new RequestContent()); + httpProcessor.addInterceptor(new RequestTargetHost()); + // Recommended protocol interceptors + httpProcessor.addInterceptor(new RequestConnControl()); + httpProcessor.addInterceptor(new RequestUserAgent()); + httpProcessor.addInterceptor(new RequestExpectContinue()); + + // execturor + httpExecutor = new HttpRequestExecutor(); + + // connection manager + connectionManager = new ConnectionManager(params); + } + + public SimpleHttpRequest(String url) throws MalformedURLException, IOException + { + this(new URL(url)); + } + + public SimpleHttpRequest(URL url) throws IOException + { + // create the request + request = new BasicHttpRequest("GET", url.toString(), HttpVersion.HTTP_1_1); + context.setAttribute(ExecutionContext.HTTP_REQUEST, request); + request.setParams(params); + + // set the host to send as a host header + HttpHost requestHost = new HttpHost(url.getHost(), url.getPort()); + context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, requestHost); + + // fetch a connection from the connection manager + connection = connectionManager.getConnection(url); + context.setAttribute(ExecutionContext.HTTP_CONNECTION, connection); + } + + public void execute() throws HttpException, IOException + { + httpExecutor.preProcess(request, httpProcessor, context); + response = httpExecutor.execute(request, connection, context); + httpExecutor.postProcess(response, httpProcessor, context); + + inputStream = response.getEntity().getContent(); + } + + public void close() + { + try + { + HttpEntity entity = response.getEntity(); + if (entity != null) + { + entity.consumeContent(); + } + } + catch (Exception e) {} + + try + { + if (inputStream != null) + { + inputStream.close(); + } + } + catch (Exception e) {} + + try + { + connectionManager.releaseConnection(connection); + } + catch (IOException e) {} + } + + public Header[] getHeader(String name) throws HttpException + { + return response.getHeaders(name); + } + + public Header[] getAllHeaders() throws HttpException + { + return response.getAllHeaders(); + } + + public long getContentLength() + { + return response.getEntity().getContentLength(); + } + + public String getContentType() + { + try + { + return response.getEntity().getContentType().getValue(); + } + catch (Exception e) + { + return null; + } + } + + public InputStream getContentStream() + { + return inputStream; + } + + public static void main(String[] args) + { + if (args.length < 1) + { + System.err.println("Please supply a URL to fetch as a first argument."); + Runtime.getRuntime().exit(1); + } + + SimpleHttpRequest request = null; + try + { + final int BUFFER_SIZE = 128; + + request = new SimpleHttpRequest(args[0]); + request.execute(); + BufferedInputStream inputStream = + new BufferedInputStream(request.getContentStream()); + + byte[] buf = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = inputStream.read(buf, 0, BUFFER_SIZE)) > -1) + { + System.out.println(new String(buf, 0, read)); + } + } + catch (MalformedURLException e) + { + System.err.println("Invalid URL."); + e.printStackTrace(); + } + catch (IOException e) + { + System.err.println("IOException caught."); + e.printStackTrace(); + } + catch (HttpException e) + { + System.err.println("HttpException caught."); + e.printStackTrace(); + } + finally + { + if (request != null) + { + request.close(); + } + } + } + } + }}} + + == ConnectionManager.java == + {{{#!java numbers=off + package org.apache.http.example; + + import java.io.IOException; + import java.net.Socket; + import java.net.URL; + import java.util.Iterator; + import java.util.LinkedList; + import java.util.List; + + import org.apache.http.impl.DefaultHttpClientConnection; + import org.apache.http.params.HttpParams; + + public class ConnectionManager + { + // max requests per connection + private static final int MAX_PERSISTENT_REQUEST = 100; + + // connection configuration parameters + private HttpParams params; + + // list of open connections + private List<HttpClientConnectionWrapper> connections; + + // wrapper class to track whether a connection is in use + private class HttpClientConnectionWrapper extends DefaultHttpClientConnection + { + boolean inUse = false; + int useCount; + } + + public ConnectionManager(HttpParams params) + { + this.params = params; + connections = new LinkedList<HttpClientConnectionWrapper>(); + } + + public DefaultHttpClientConnection getConnection(URL url) + throws IOException + { + // check to see if we have an available connection + synchronized (connections) + { + Iterator<HttpClientConnectionWrapper> iter = connections.iterator(); + while (iter.hasNext()) + { + HttpClientConnectionWrapper connection = iter.next(); + + // if the connection is closed remove it + if (!connection.isOpen()) + { + iter.remove(); + continue; + } + + // it's open, is it in use? + if (!connection.inUse) + { + connection.inUse = true; + connection.useCount++; + return connection; + } + } + } + + // we haven't found one, make a new one + return makeNewConnection(url); + } + + private DefaultHttpClientConnection makeNewConnection(URL url) + throws IOException + { + Socket socket = new Socket(url.getHost(), url.getPort()); + + HttpClientConnectionWrapper connection = new HttpClientConnectionWrapper(); + connection.bind(socket, params); + connection.inUse = true; + synchronized (connections) + { + connections.add(connection); + } + return connection; + } + + public void releaseConnection(DefaultHttpClientConnection connection) + throws IOException + { + if (!(connection instanceof HttpClientConnectionWrapper)) + { + throw new IllegalArgumentException("*slap* Invalid connection."); + } + HttpClientConnectionWrapper con = ((HttpClientConnectionWrapper)connection); + + // reached max keep-alive requests, close it + if (con.useCount >= MAX_PERSISTENT_REQUEST) + { + con.close(); + connections.remove(con); + return; + } + + con.inUse = false; + } + } + }}} + --------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
