zeeshanejaz / unirest-android

This is an android port of unirest-java
MIT License
32 stars 13 forks source link

Unirest for Android

This is an android port of unirest-java project (https://github.com/Mashape/unirest-java). It uses localized copies of the latest Apache HTTP Components which are not yet available on MavenCentral repo for android projects.

Unirest is a set of lightweight HTTP libraries available in multiple languages, ideal for most applications:

Created with love by thefosk @ mashape.com

Ported by: Zeeshan Ejaz Bhatti

Installing

Installing unirest-android is easy. It is available on custom maven repository.

With Maven

You will have to do two things namely, add the repository and the dependency.

Firstly:

<repositories>
  ...
  <repository>
    <id>unirest-for-android</id>
    <url>https://raw.github.com/zeeshanejaz/unirest-android/mvn-repo</url>
  </repository>
  ...
</repositories>

and then:

<dependencies>
  ...
  <dependency>
    <groupId>com.mashape.unirest</groupId>
    <artifactId>unirest-android</artifactId>
    <version>1.0.1</version>
  </dependency>
  ...
</dependencies>

With Gradle

With Gradle, you will have to add reference to the repository and dependency in you build.gradle file i.e., the following.

repositories {
        ...
        maven{
            url 'https://raw.github.com/zeeshanejaz/unirest-android/mvn-repo'
        }
    }
...
dependencies {
    ...
    compile 'com.mashape.unirest:unirest-android:1.0+'
}

Asynchronous Requests

Sometimes, well most of the time, you want your application to be asynchronous and not block, Unirest supports this in Java using anonymous callbacks, or direct method placement:

Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .field("param1", "value1")
  .field("param2", "value2")
  .asJsonAsync(new Callback<JsonNode>() {

    public void failed(UnirestException e) {
        System.out.println("The request has failed");
    }

    public void completed(HttpResponse<JsonNode> response) {
         int code = response.getCode();
         Map<String, String> headers = response.getHeaders();
         JsonNode body = response.getBody();
         InputStream rawBody = response.getRawBody();
    }

    public void cancelled() {
        System.out.println("The request has been cancelled");
    }

});

File Uploads

Creating multipart requests with Java is trivial, simply pass along a File Object as a field:

HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .field("parameter", "value")
  .field("file", new File("/tmp/file"))
  .asJson();

Custom Entity Body

HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .body("{\"parameter\":\"value\", \"foo\":\"bar\"}")
  .asJson();

Basic Authentication

Authenticating the request with basic authentication can be done by calling the basicAuth(username, password) function:

HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/headers").basicAuth("username", "password").asJson();

Request

The Java Unirest library follows the builder style conventions. You start building your request by creating a HttpRequest object using one of the following:

HttpRequest request = Unirest.get(String url);
HttpRequestWithBody request = Unirest.post(String url);
HttpRequestWithBody request = Unirest.put(String url);
HttpRequestWithBody request = Unirest.patch(String url);
HttpRequestWithBody request = Unirest.delete(String url);

Response

Upon recieving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details.

Advanced Configuration

You can set some advanced configuration to tune Unirest-Java:

Custom HTTP clients

You can explicitly set your own HttpClient and HttpAsyncClient implementations by using the following methods:

Unirest.setHttpClient(httpClient);
Unirest.setAsyncHttpClient(asyncHttpClient);

Timeouts

You can set custom connection and socket timeout values (in milliseconds):

Unirest.setTimeouts(long connectionTimeout, long socketTimeout);

By default the connection timeout is 10000, and the socket timeout is 60000.

Default Request Headers

You can set default headers that will be sent on every request:

Unirest.setDefaultHeader("Header1", "Value1");
Unirest.setDefaultHeader("Header2", "Value2");

You can clear the default headers anytime with:

Unirest.clearDefaultHeaders();

Exiting an application

If you are using the asynchronous client, a background event loop is started and your Java application won't be able to exit until you manually shutdown all the threads by invoking:

Unirest.shutdown();