天天看点

轻量级的HTTP开发库 Unirest UNIREST-JAVA

原文:http://unirest.io

is easy as pie. kidding. it's about as easy as doing these little steps:

using with maven by adding the mashape repository:

and including the library:

there are dependencies for the java library, these should be already installed, and they are as follows:

so you're probably wondering how using unirest makes creating requests in java easier, here is a basic post request that will explain everything:

requests are made when as[type]() is invoked, possible types include json, binary, string.

if the request supports and it is of type httprequestwithbody, a body it can be passed along with .body(string|jsonnode).

if you already have a map of parameters or do not wish to use seperate field methods for each one there is a .fields(map<string, object> fields) method that will serialize each key

- value to form parameters on your request.

.headers(map<string, string> headers) is also supported in replacement of multiple header methods.

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:

creating multipart requests with java is trivial, simply pass along a file object as a field:

the java unirest library follows the builder style conventions. you start building your request by creating a httprequest object using one of the following:

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.

.getcode()

http response status code (example 200)

.getheaders()

http response headers

.getbody()

parsed response body where applicable, for example json responses are parsed to objects / associative arrays.

.getrawbody()

un-parsed response body