Skip to content

GettingStarted

zhenya edited this page Feb 4, 2020 · 2 revisions

Calls

NanoHTTP's main job is to send your requests to the HTTP server and parse the responses returned by the HTTP server in a convenient way.

The "Hard" way:

Without using a third party client to make HTTP calls in Java you would have to write code like this:

final URL resource = ...
final HttpURLConnection connection = (HttpURLConnection) resource.openConnection();

connection.setRequestMethod("GET");  // default

try (final InputStream in = connection.getInputStream()) {  
   final ByteArrayOutputStream out = new ByteArrayOutputStream();

   int n;
   byte[] buffer = new byte[1024];
   while ((n = in.read(buffer, 0, buffer.length)) != -1)
      out.write(buffer, 0, n);

   final byte[] bytes = out.toByteArray();
   final String text = new String(bytes); // platform's default charset

   System.out.println(text);
} catch (final IOException e) {    
   e.printStackTrace();
}

There are several problems with the above code. First, we did not check the Content-Type to see if a charset was specified. The resulting string may be unreadable if the default charset does not match the charset specified in the response. Second, if an error occurred, we will have very little information about what happened. HttpURLConnection throws IOExceptions which do not parse or even provide access to the headers returned by the server.

Making a simple GET request

Now let's see what the same call would like with NanoHTTP.

final URL resource = ...

final HttpClient client = HttpClient.defaultClient();
final HttpRequest request = client.get(resource);

try (final HttpResponse response = request.send()) {
   final ResponseBody body = response.getBody();
   final String text = body.asString(); // will use the charset specified in the Content-Type header
   System.out.println(text);
} catch (final HttpResponseException e) {
   System.err.println(e.getMessage()); // the status-line returned by the server
   System.err.println(e.getErrorMessage()); // the response message returned by the server
}
   

But if that still seems verbose, let's see how fluent the NanoHTTP API is:

final URL resource = ...
   
try (final HttpResponse response = HttpClient.defaultClient().get(resource).send()) {
   System.out.println(response.getBody().asString());
}

Any exceptions will be propagated.

Making a simple POST request

final URL resource = ...
   
final ByteArrayBody body = ByteArrayBody.encode("Hello, World!");
        
final HttpClient client = HttpClient.defaultClient();
try (final HttpResponse response = client.post(resource).setBody(body).setContentType("text/plain; charset=utf-8").send()) {
   ...
}