Search code examples
javacurlunirestnoaa

Unirest Headers Request Body


I've got a quick question about making a Unirest Request with headers.

I am using the NOAA API to access weather information. They ask that you send a header with the following, but it is in CURL and I need help converting it to Java to make a Unirest Request:

curl -H "token:<token>" "url"
$.ajax({ url:<url>, data:{<data>}, headers:{ token:<token> } })

This is the URL of the documentation if it helps: https://www.ncdc.noaa.gov/cdo-web/webservices/v2#gettingStarted

And here is the endpoint I am trying to access: https://www.ncdc.noaa.gov/cdo-web/api/v2/datatypes/

This is probably something very simple, but I can't figure it out for the life of me!

Thanks for the help in advance!


Solution

  • Unirest is actually not that daunting to work with. All you need to do is set a token value as header and you're set. You can use this snippet:

    HttpResponse<JsonNode> response = null;
    
    try {
        response = Unirest.get("https://www.ncdc.noaa.gov/cdo-web/api/v2/datatypes")
                .header("token", "YOUR_TOKEN_HERE")
                .asJson();
    } catch (UnirestException e) {
        //Uh oh!
        e.printStackTrace();
    }
    
    System.out.println(response.getBody());
    

    If you'd prefer to retrieve as a String instead you could replace HttpResponse<JsonNode> by HttpResponse<String> and asJson() by asString().

    You can find much more useful information here.