Home > front end >  REST api request (Cannot make a static reference to the non-static method)
REST api request (Cannot make a static reference to the non-static method)

Time:12-08

I was Following a tutorial; https://www.youtube.com/watch?v=9oq7Y8n1t00&ab_channel=CodingwithJohn And all that I want to do is to send a get to the NASA api.

import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublisher;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse.BodyHandlers;
public class Output {
    
    public static void config(String input) {
        if (input == "news") {

            try {
                HttpRequest getRequest = HttpRequest.newBuilder()
                    .uri(new URI("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")) //Demo key, (replace later)
                    .build();
               // HttpResponse<String> response = client.send(getRequest, BodyHandlers.ofString());
                 HttpResponse<String> getResponse = HttpClient.send(getRequest, BodyHandlers.ofString());

            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
        }
}
}

It tells me: "Cannot make a static reference to the non-static method send(HttpRequest,HttpResponse.BodyHandler ) from the type HttpClient"

How do I get by this. My ultimate goal is to use the api in java,

CodePudding user response:

You have to create an instance of HttpClient in this way

HttpClient client = HttpClient.newHttpClient();

and then use the line that you commented

HttpResponse<String> response = client.send(getRequest, BodyHandlers.ofString());
  • Related