Skip to content
wizzardo edited this page Aug 17, 2014 · 6 revisions

HttpClient

Basic idea is:

  • create request
  • set parameters and headers
  • execute request by methods get/post/execute
  • get response object
  • read response as string/bytes, get response code, headers

Simple Get request:

new Request("url").get().asString()

Let’s add some parameters

new Request("url")
    .param("key","value")
    .param("foo","bar")
    .get()
    .asBytes()

Or maybe you want to upload file:

new Request("url")
    .addFile("fieldName", "path to file on disk") 
    .addByteArray("array", data, "fileName")
// by adding file or byte[] you will create a multipart request
    .post()
    .getResponseCode()

If you want to make simple Post request with data:

new Request("url")
    .data(bytes, ContentType.BINARY)
    .post()
    .asString()

To save session between requests you can use HttpSession, also you can set default request parameters:

HttpSession session = new HttpSession()
    .header("Accept", ContentType.JSON.value);
        
session.createRequest("url")
    .json("{}") 
// set json-string as request body and content type to application/json 
    .execute()
    .asString();

HttpClient class has its own HttpSession, so it saves cookies for all requests made through it.

Clone this wiki locally