Giter VIP home page Giter VIP logo

basic-http-client's Introduction

[JavaDoc] (http://javadoc.basic-http-client.googlecode.com/git/docs/index.html) | Blog post

#Basic HTTP Client for Java (including App Engine and Android)#

A minimal HTTP client that uses java.net.HttpURLConnection to make requests. It features a simple interface for making Web requests. There is also an AsyncHttpClient which supports making asynchronous requests with retries and exponential backoff, and AndroidHttpClient which wraps requests in an Android AsyncTask so that requests can be safely initiated from the UI thread.

##Lightning Start##

  1. Download one of the jars at left and add it to your lib or libs (Android) folder
  2. (Android only) Add <uses-permission android:name="android.permission.INTERNET" /> to !AndroidManifest.xml

##Quick Start##

  1. git clone https://github.com/turbomanage/basic-http-client.git
  2. In Eclipse, Import | Existing Projects into Workspace and point it to the basic-http-client dir
  3. To include the library in another project, add the basic-http-client project to the build path OR
  4. For Android projects, create a linked source folder named httpclient-src that points to basic-http-client/src

Maven

In your Java project (including App Engine for Java), add this to your pom.xml:

<dependency>
    <groupId>com.turbomanage.basic-http-client</groupId>
    <artifactId>http-client-java</artifactId>
    <version>0.89</version>
</dependency>

Gradle (Android)

If your Android project builds with Gradle, add this to your app's gradle.build:

dependencies {
    ...
    compile 'com.turbomanage.basic-http-client:http-client-android:0.89'
}

##Basic Usage##

// Example code to login to App Engine dev server
public void loginDev(String userEmail) {
    BasicHttpClient httpClient = new BasicHttpClient("http://localhost:8888");
    ParameterMap params = httpClient.newParams()
            .add("continue", "/")
            .add("email", userEmail)
            .add("action", "Log In");
    httpClient.addHeader("name", "value");
    httpClient.setConnectionTimeout(2000);
    HttpResponse httpResponse = httpClient.post("/_ah/login", params);
}

// Example code to log in to App Engine production app
public void loginProd(String authToken) {
    BasicHttpClient httpClient = new BasicHttpClient("http://localhost:8888");
    ParameterMap params = httpClient.newParams()
            .add("auth", authToken);
    HttpResponse httpResponse = httpClient.get("/_ah/login", params);
    System.out.println(httpResponse.getBodyAsString());
}

##Making Asynchronous Requests## The project includes an !AsyncTask wrapper for Android so that requests can be safely initiated on the UI thread with a callback. Example:

AndroidHttpClient httpClient = new AndroidHttpClient("http://192.168.1.1:8888");
httpClient.setMaxRetries(5);
ParameterMap params = httpClient.newParams()
        .add("continue", "/")
        .add("email", "[email protected]")
        .add("action", "Log In");
httpClient.post("/_ah/login", params, new AsyncCallback() {
    @Override
    public void onSuccess(HttpResponse httpResponse) {
        System.out.println(httpResponse.getBodyAsString());
    }
    @Override
    public void onError(Exception e) {
        e.printStackTrace();
    }
});

App Engine for Java

The basic-http-client project simply wraps java.net.UrlConnection. On App Engine, this in turn wraps the App Engine URLFetch API. The net result is that you can use version 0.89 or later to make outbound requests from your server application.

Cookies

In AndroidHttpClient, java.net.CookieManager is enabled by default above API version 8 (when it was introduced) in order to save cookies between requests and resend them just like a browser does.

Prior to version 0.89, BasicHttpClient would also automatically enable java.net.CookieManager. However, this is not supported on App Engine, so in version 0.89 and later, you must explicitly enable cookie support. Before making the first request, simply call the static method

AbstractHttpClient.ensureCookieManager();

##Understanding the Code## The key method is AbstractHttpClient.doHttpMethod(String path, HttpMethod httpMethod, String contentType, byte[] content). This is the method that actually drives each request, catches any exceptions, and rethrows them wrapped in an HttpRequestException. It delegates most of the request lifecycle to a RequestHandler instance. To override the default behaviors (say, to provide your own error handler or custom stream reader/writer), simply extend the BasicRequestHandler like this:

        BasicHttpClient client = new BasicHttpClient(baseUrl, new BasicRequestHandler() {
            @Override
            public boolean onError(HttpResponse res, Exception e) {
                e.printStackTrace();
                return true; // if recoverable
            }
        });

##Advanced Usage## To create an async client for another platform, simply subclass AsyncHttpClient and provide it with an instance of a AsyncRequestExecutorFactory suitable for your platform. See the com.turbomanage.httpclient.android package for the Android implementation which uses AsyncTask.

basic-http-client's People

Contributors

davidawad avatar turbomanage avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.