Search code examples
javajsonunirest

Get request using Unirest to get a JSON stream


I am trying to establish this GET request:

 http://api.bitcoincharts.com/v1/trades.csv?symbol=krakenUSD&start=1303100000

When I do this using postman, it works out perfectly. However, when I do this using an HttpRequest the body of the request returns as a null object.

            HttpRequest r = Unirest.get("http://api.bitcoincharts.com/v1/trades.csv").queryString("symbol", "krakenUSD").queryString("start", "1303100000");
            System.out.println(r.getUrl());
            System.out.println(r.getBody().toString());

I get a null pointer error at:

 System.out.println(r.getBody().toString());

What is the proper way to submit this GET request? I am not sure if queryString() is what I should use?


Solution

  • First, the request you are making might not return JSON. Look at the endpoint URL:

    "http://api.bitcoincharts.com/v1/trades.csv"

    It most likely returns CSV, not JSON.

    If the content type is 'application/json' or the URL is *.json, you have to invoke the .asJson method:

    Unirest.post(URL)
      .queryString("symbol", "krakenUSD")
      .queryString("start", "1303100000")
      .asJson()
    

    Reference: http://unirest.io/java.html