• Stars
    star
    3,304
  • Rank 13,493 (Top 0.3 %)
  • Language
    Java
  • License
    MIT License
  • Created almost 13 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Java HTTP Request Library

Http Request Build Status

A simple convenience library for using a HttpURLConnection to make requests and access the response.

This library is available under the MIT License.

Usage

The http-request library is available from Maven Central.

<dependency>
  <groupId>com.github.kevinsawicki</groupId>
  <artifactId>http-request</artifactId>
  <version>6.0</version>
</dependency>

Not using Maven? Simply copy the HttpRequest class into your project, update the package declaration, and you are good to go.

Javadocs are available here.

FAQ

Who uses this?

See here for a list of known projects using this library.

Why was this written?

This library was written to make HTTP requests simple and easy when using a HttpURLConnection.

Libraries like Apache HttpComponents are great but sometimes for either simplicity, or perhaps for the environment you are deploying to (Android), you just want to use a good old-fashioned HttpURLConnection. This library seeks to add convenience and common patterns to the act of making HTTP requests such as a fluid-interface for building requests and support for features such as multipart requests.

Bottom line: The single goal of this library is to improve the usability of the HttpURLConnection class.

What are the dependencies?

None. The goal of this library is to be a single class class with some inner static classes. The test project does require Jetty in order to test requests against an actual HTTP server implementation.

How are exceptions managed?

The HttpRequest class does not throw any checked exceptions, instead all low-level exceptions are wrapped up in a HttpRequestException which extends RuntimeException. You can access the underlying exception by catching HttpRequestException and calling getCause() which will always return the original IOException.

Are requests asynchronous?

No. The underlying HttpUrlConnection object that each HttpRequest object wraps has a synchronous API and therefore all methods on HttpRequest are also synchronous.

Therefore it is important to not use an HttpRequest object on the main thread of your application.

Here is a simple Android example of using it from an AsyncTask:

private class DownloadTask extends AsyncTask<String, Long, File> {
  protected File doInBackground(String... urls) {
    try {
      HttpRequest request =  HttpRequest.get(urls[0]);
      File file = null;
      if (request.ok()) {
        file = File.createTempFile("download", ".tmp");
        request.receive(file);
        publishProgress(file.length());
      }
      return file;
    } catch (HttpRequestException exception) {
      return null;
    }
  }

  protected void onProgressUpdate(Long... progress) {
    Log.d("MyApp", "Downloaded bytes: " + progress[0]);
  }

  protected void onPostExecute(File file) {
    if (file != null)
      Log.d("MyApp", "Downloaded file to: " + file.getAbsolutePath());
    else
      Log.d("MyApp", "Download failed");
  }
}

new DownloadTask().execute("http://google.com");

Examples

Perform a GET request and get the status of the response

int response = HttpRequest.get("http://google.com").code();

Perform a GET request and get the body of the response

String response = HttpRequest.get("http://google.com").body();
System.out.println("Response was: " + response);

Print the response of a GET request to standard out

HttpRequest.get("http://google.com").receive(System.out);

Adding query parameters

HttpRequest request = HttpRequest.get("http://google.com", true, 'q', "baseball gloves", "size", 100);
System.out.println(request.toString()); // GET http://google.com?q=baseball%20gloves&size=100

Using arrays as query parameters

int[] ids = new int[] { 22, 23 };
HttpRequest request = HttpRequest.get("http://google.com", true, "id", ids);
System.out.println(request.toString()); // GET http://google.com?id[]=22&id[]=23

Working with request/response headers

String contentType = HttpRequest.get("http://google.com")
                                .accept("application/json") //Sets request header
                                .contentType(); //Gets response header
System.out.println("Response content type was " + contentType);

Perform a POST request with some data and get the status of the response

int response = HttpRequest.post("http://google.com").send("name=kevin").code();

Authenticate using Basic authentication

int response = HttpRequest.get("http://google.com").basic("username", "p4ssw0rd").code();

Perform a multipart POST request

HttpRequest request = HttpRequest.post("http://google.com");
request.part("status[body]", "Making a multipart request");
request.part("status[image]", new File("/home/kevin/Pictures/ide.png"));
if (request.ok())
  System.out.println("Status was updated");

Perform a POST request with form data

Map<String, String> data = new HashMap<String, String>();
data.put("user", "A User");
data.put("state", "CA");
if (HttpRequest.post("http://google.com").form(data).created())
  System.out.println("User was created");

Copy body of response to a file

File output = new File("/output/request.out");
HttpRequest.get("http://google.com").receive(output);

Post contents of a file

File input = new File("/input/data.txt");
int response = HttpRequest.post("http://google.com").send(input).code();

Using entity tags for caching

File latest = new File("/data/cache.json");
HttpRequest request = HttpRequest.get("http://google.com");
//Copy response to file
request.receive(latest);
//Store eTag of response
String eTag = request.eTag();
//Later on check if changes exist
boolean unchanged = HttpRequest.get("http://google.com")
                               .ifNoneMatch(eTag)
                               .notModified();

Using gzip compression

HttpRequest request = HttpRequest.get("http://google.com");
//Tell server to gzip response and automatically uncompress
request.acceptGzipEncoding().uncompress(true);
String uncompressed = request.body();
System.out.println("Uncompressed response is: " + uncompressed);

Ignoring security when using HTTPS

HttpRequest request = HttpRequest.get("https://google.com");
//Accept all certificates
request.trustAllCerts();
//Accept all hostnames
request.trustAllHosts();

Configuring an HTTP proxy

HttpRequest request = HttpRequest.get("https://google.com");
//Configure proxy
request.useProxy("localhost", 8080);
//Optional proxy basic authentication
request.proxyBasic("username", "p4ssw0rd");

Following redirects

int code = HttpRequest.get("http://google.com").followRedirects(true).code();

Custom connection factory

Looking to use this library with OkHttp? Read here.

HttpRequest.setConnectionFactory(new ConnectionFactory() {

  public HttpURLConnection create(URL url) throws IOException {
    if (!"https".equals(url.getProtocol()))
      throw new IOException("Only secure requests are allowed");
    return (HttpURLConnection) url.openConnection();
  }

  public HttpURLConnection create(URL url, Proxy proxy) throws IOException {
    if (!"https".equals(url.getProtocol()))
      throw new IOException("Only secure requests are allowed");
    return (HttpURLConnection) url.openConnection(proxy);
  }
});

Contributors

More Repositories

1

tray-example

Electron Tray Mac OS X Example App
JavaScript
432
star
2

wishlist

Utilities I wish Android had but doesn't
Java
383
star
3

monokai

Monokai Atom Syntax theme
Less
241
star
4

github-maven-example

Example project using GitHub Maven Plugins
Java
135
star
5

gitective

Find the Git commits you're looking for
Java
116
star
6

birthday-pizza

It's probably your birthday somewhere
HTML
108
star
7

java-timeago

Java timeago library
Java
66
star
8

signcode

Codesign Windows executables from a Mac
JavaScript
42
star
9

etag-cache

HTTP requests backed by an ETag cache
Java
30
star
10

dotfiles

Files that start with a β€’
CSS
26
star
11

git-reports

Report generator for Git activity
Java
21
star
12

stock-quotes

Java library for the Google Finance Historical Prices API
Java
20
star
13

faceoff

World Cup Primer
HTML
17
star
14

filings

Node module for SEC filings
CoffeeScript
15
star
15

github-api-examples

Examples using the GitHub Java API
Java
15
star
16

hindstock

Android app to calculate stock gains & losses
Java
13
star
17

ceo-sell

When CEOs sell stock in their own company
JavaScript
12
star
18

command-logger

Treemap of which commands you run in Atom
CoffeeScript
11
star
19

jgit-mongo

JGit MongoDB connector
Java
10
star
20

android-utils

Android Utilities
Java
9
star
21

grunt-cson

Compile CSON files with Grunt
CoffeeScript
8
star
22

coffeestack

CoffeeScript Stacktrace Converter
CoffeeScript
8
star
23

gitng-plugin

New Git Jenkins Plugin
Java
8
star
24

mac-extension-icon

Node module to get the default Finder icon for a file extension (macOS only)
Objective-C++
8
star
25

electron-atos

Symbolicate an Electron macOS crash report
JavaScript
7
star
26

jgit.info

JGit Community Book
6
star
27

jgit-redis

JGit Redis connector
Java
6
star
28

github-api-request

http-request connector for the GitHub Java API
Java
4
star
29

halligan

JSON Hypermedia API Language (HAL) Java Library
Java
4
star
30

snapshot-benchmark

Experiments measuring how V8 snapshots can improve Electron app load time
JavaScript
4
star
31

kanye-kim

kanye.kim the website
HTML
3
star
32

ebay-eclipse-demo-camp

Presentation for December 2011 Eclipse DemoCamp @eBay
3
star
33

lettergize

Images to ASCII art as a service
CoffeeScript
3
star
34

eclipse-avatar

Eclipse Gravatar Plug-in
Java
3
star
35

eclipse-oauth2

Eclipse plug-in to get an OAuth2 access token
Java
2
star
36

eclipseday-ignite-2011

Ignite slides for Eclipse Day at Googleplex 2011
2
star
37

garbage

2
star
38

tenk

Form 10-K data visualized
CoffeeScript
2
star
39

indigo-demo-camp

Presentation for Eclipse Indigo Demo Camp
JavaScript
2
star
40

empty-empty

2
star
41

doogie-syntax

Doogie Howser Journal Atom Syntax Theme
CSS
2
star
42

jaxconf-2011

Presentation for JAX conference 2011
JavaScript
2
star
43

seajects

Generate object models from ctags output
Ruby
2
star
44

node-docs

JavaScript
1
star
45

little-debbie

automake, autoconf, debhelper example
Shell
1
star
46

git-rot

Atom package to show Git age information
CoffeeScript
1
star
47

mac-active-url

Get the URL of the document in the focused window (Mac only)
Objective-C++
1
star
48

browsetron

Simple browser example built on Electron
JavaScript
1
star
49

sandpiper

Parse useful SEC data
CoffeeScript
1
star
50

codechix-test-repo

CodeChix Git Workshop Test Repository
1
star