Home > Blockchain >  Get access to a key in Java HttpClient response
Get access to a key in Java HttpClient response

Time:01-04

New to API's in Java. I'm trying to get a response from an API and print some of it. My response in the code below prints the whole dictionary, but I want to print just part of it. In the current way, I have no idea how I can get access to the dictionary, as my response is a String and I couldn't find a relevant BodyHandlers method. How can I do that? Thanks a lot.

This is my code:


HttpRequest urlAnalysisRequest = HttpRequest.newBuilder()
                    .uri(URI.create("https://www.virustotal.com/api/v3/analyses/....(I put the id here)"))
                    .header("Accept", "application/json")
                    .header("x-apikey", "....(I put api key here)")
                    .method("GET", HttpRequest.BodyPublishers.noBody())
                    .build();
                HttpResponse<String> urlAnalysisResponse;
                try {
                    urlAnalysisResponse = HttpClient.newHttpClient().send(urlAnalysisRequest, HttpResponse.BodyHandlers.ofString());
                                        
                    System.out.println(urlAnalysisResponse.body());
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

This is my response. I'm trying to get "stats":


{
    "meta": {
        "url_info": {
            "url": "http://www.facebook.com/",
            "id": "114fb86b9b4e868f8bac2249eb5c444b545f0240c3dadd23312a0bc1622b5488"
        }
    },
    "data": {
        "attributes": {
            "date": 1641238171,
            "status": "completed",
            "stats": {
                "harmless": 84,
                "malicious": 0,
                "suspicious": 0,
                "undetected": 9,
                "timeout": 0
            },
..........

CodePudding user response:

The response is written in a format known as JSON. You need a library to parse this. There are a few options; I strongly suggest you go with Jackson.

You can choose to refer to it with string paths, or, you can make a java class that 'matches' this output, e.g:

class VirusTotalResponse {
  VTMeta meta;
  VTData data;
}

class VTMeta {
  VTUrlInfo urlInfo;
}

class VTUrlInfo {
  String url;
  String id;
}

and so on. With all those classes in place, turn them all into proper classes (use your IDE's various options, or use Project Lombok) and then just ask Jackson to turn that response into an instance of VirusTotalResponse and you'll have a nice shiny java object, you can then just:

  int harmless = response.getData().getAttributes().getStats().getHarmless();

CodePudding user response:

You can use ObjectMapper which is library for handling JSON data easily. You can use not only Class for mapping, but also Map.

I recommend this tutorial site.

  •  Tags:  
  • Related