0

i'm creating java module to parse JSON file.

To receive file i need to send HTTP request. When I use curl my request looks like this:

curl -X GET "https://***" -H "accept: application/json" -H "apikey: ***"

How can I send the equivalent HTTP request from Java

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
Ilkar
  • 2,113
  • 9
  • 45
  • 71

3 Answers3

3

Java has a lot of options to work with HTTP.

Option 1

Since Java 9, there is a built-in HTTP client. So You can use it to create a request without any third-party libraries.

A simple example is something like this:

HttpRequest request2 = HttpRequest.newBuilder()
  .uri(new URI("some url"))
  .header("someHeader", "value1")
  .header("anotherHeader", "value2")
  .GET()
  .build();

For more examples see here

Option 2

Use third party libraries, there are many: OkHttpClient, More "old-school" Apache Http Client (HttpComponents

Option 3

If you're using spring, you might consider using Spring's WebClient. There are also wrappers in spring like RestTemplate that can come handy, but it really depends on what would you like to work with.

Many clients are coming with http connection pools that should be properly set up. In addition, in your example, I see that you work with https - all these clients support it but it should be properly set up.

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
  • If i want to use option 1, how shall is use POST() instead of GET() in HttpRequest? Could you please help? – Ananth Kamath Dec 27 '21 at 05:27
  • Have you checked the link I've provided in the answer? (The one that starts wuth "For more examples see here") It contains an example of POST requests. Usually these requests come with Body, but this is related to HTTP in general and not to a particular http client, so you'll have to grasp this concept anyway. – Mark Bramnik Dec 27 '21 at 08:18
0

If you are using Spring then try WebClient - it is a bit harder to understand in the begging (at least harder than RestTemplate) but it pays of since RestTemplate will be discontinued.

You can find an example here

https://www.baeldung.com/spring-webclient-resttemplate

@GetMapping(value = "/tweets-non-blocking", 
            produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Tweet> getTweetsNonBlocking() {
    log.info("Starting NON-BLOCKING Controller!");
    Flux<Tweet> tweetFlux = WebClient.create()
      .get()
      .uri(getSlowServiceUri())
      .retrieve()
      .bodyToFlux(Tweet.class);

    tweetFlux.subscribe(tweet -> log.info(tweet.toString()));
    log.info("Exiting NON-BLOCKING Controller!");
    return tweetFlux;
}

Just be aware that this is non-blocking (e.g. asynchronous) solution so you won't get the response right away, but you subscribe to the request and then process the response when it is available. There are also blocking options in WebClient

hocikto
  • 871
  • 1
  • 14
  • 29
  • This is Spring specific solution. OP asked for a very general option to send HTTP request from Java. – Michael Gantman Jan 18 '21 at 13:22
  • @MichaelGantman he did not say not to use any framework though so why the downvote, there are many options, spring is one of them – hocikto Jan 18 '21 at 13:24
  • You are correct - Spring is one of the options. If he uses spring then yes, that would be a way to do it. But if he doesn't then to use Spring just to make a simple HTTP request is huge overshot. Plus your answer is misleading making him think that if he needs to send HTTP request Spring would be the first option to think about. There are by far more simpler ways to send HTTP request. Hence the downvote. (Please don't take it personally). – Michael Gantman Jan 18 '21 at 13:29
  • @MichaelGantman I don't. I think the answer by Mark Bramnik is the best since it provides multiple approaches, this was just first that came to my mind, I have not thought of the possibility that the OP could be misled that he needs a 3rd party framework, so I'll take that to my future answers. – hocikto Jan 18 '21 at 13:46
0

Java has its own classes that allow you to send HTTP request. See class HttpURLConnection. However, I recommend using 3d party libraries that significantly simplify this task. Good libraries would be Apache Http client or OK Http client. I also can offer you to use another Open source library that has an HTTP client as well. It is called MgntUtils library and it is written by me. In this case your code would look something like this:

            HttpClient workingClient = new HttpClient();
            workingClient.setRequestProperty("accept", "application/json;charset=UTF-8");
            workingClient.setRequestProperty("apikey", "***");
            workingClient.setConnectionUrl("https://***");
            ByteBuffer buffer = 
            workingClient.sendHttpRequestForBinaryResponse(HttpMethod.GET);
            
            //or of your API returns contents of file as a string
            String jsonStr = workingClient.sendHttpRequest(HttpMethod.GET);

After that, your ByteBuffer buffer or String jsonStr will hold the content of your JSON file. And now you can do whatever you need with it. Here is Javadoc for HttpClient class. The MgntUtils library can be obtained as maven artifacts here or on Github (including source code and Javadoc)

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36