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

5
  • Maybe this will help you baeldung.com/java-curl Commented Jan 18, 2021 at 12:35
  • Are you using native Java, this can be easy if you are using Spring boot for example! Commented Jan 18, 2021 at 12:37
  • Take a look also to RestTemplate maybe it can help you Commented Jan 18, 2021 at 12:39
  • RestTemplate will be discontinued so if you are planning to make this long-term solution try WebClient from Spring Commented Jan 18, 2021 at 13:08
  • Does this answer your question? How to use java.net.URLConnection to fire and handle HTTP requests Commented Dec 31, 2021 at 19:12

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If i want to use option 1, how shall is use POST() instead of GET() in HttpRequest? Could you please help?
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.
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

4 Comments

This is Spring specific solution. OP asked for a very general option to send HTTP request from Java.
@MichaelGantman he did not say not to use any framework though so why the downvote, there are many options, spring is one of them
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).
@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.
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)

Comments

0

To trigger a simple get request we can use following code

@GetMapping("triggersimpleget")
public void triggersimpleget() {
    try {
        /**
         * request will be sent to url
         */
        String url = "http://localhost:1818/simpleget";
        HashMap<String, String> queryparams = new HashMap<String, String>();
        /**
         * setting header to accept json
         */
        RestTemplate restTemplate = new RestTemplate();//instead of this we can create a bean and autowire it.
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        HttpEntity<?> httpEntity = new HttpEntity<>(headers);
        /**
         * exchange( urltobehit, httpmethod, header, response, urivaraibles
         * we are sending get request and expecting boolean response
         */
        ResponseEntity<Boolean> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Boolean.class);
        if (response.getStatusCodeValue() == HttpStatus.OK.value()) {
            /**
             * Printing Resoponse body
             */
            System.out.println("test makes call successful :: " + response.getBody());
        } else {
            System.err.println("Error while test making call");
        }
    } catch (HttpStatusCodeException exception) {
        /**
         * to get status code for exception
         */
        System.err.println(exception);
    } catch (Exception e) {
        /**
         * Other exception
         */
        System.err.println(e);
    }
}

the above method will send request to following method in which @corsorigin is added as this for demo

@GetMapping("simpleget")
@CrossOrigin /** to allow request from any origin **/
public boolean simpleget() {
    System.out.println("Thank you i received the hit");
    return true;
}

for testing we can hit following url

http://localhost:port/triggersimpleget

To send get request with query parameter we can use following code

@GetMapping("hitwithqueryparam")
public void test(@RequestParam(value = "input1") String input1, @RequestParam(value = "input2") String input2) {
    /**
     * This method takes two input and calls testtwo endpoint passing query parameter
     */
    try {
        String url = "http://localhost:1818/acceptqueryparam?string1={firstinput}&string2={secondinput}";
        HashMap<String, String> queryparams = new HashMap<String, String>();
        /**
         * Building and mapping query parameter
         */
        queryparams.put("firstinput", input1); //will map values into the curly bracket as query param {}
        queryparams.put("secondinput", input2);//will map values into the curly bracket as query param {}

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        
        HttpEntity<?> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<Boolean> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Boolean.class,queryparams);
        if (response.getStatusCodeValue() == HttpStatus.OK.value()) {
            /**
             * Printing Resoponse body
             */
            System.out.println("test makes call successful :: " + response.getBody());
        } else {
            System.err.println("Error while test making call");
        }
    } catch (HttpStatusCodeException exception) {
        System.err.println(exception);
    } catch (Exception e) {
        System.err.println(e);
    }
}

Below method will accept and print the query param

@GetMapping("acceptqueryparam")
@CrossOrigin
public boolean acceptqueryparam(@RequestParam(value = "string1") String string1,
        @RequestParam(value = "string2") String string2) {
    /**
     * endpoint accepts query parameter as input and prints
     */
    if (string1.length() != 0 && string2.length() != 0) {
        System.out.println("Receieved " + string1 + " and " + string2);
        return true;
    }
    return false;
}

To trigger post request following is the code

@GetMapping("triggersimplepost")
public void triggersimplepost() {
    try {
        /**
         * request will be sent to url
         */
        String url = "http://localhost:1818/simplepost";
        HashMap<String, String> reqpayload = new HashMap<String, String>();
        reqpayload.put("user", "john");
        /**
         * setting header to accept json
         */
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        /**
         * Adding request payload.
         */
        HttpEntity<?> httpEntity = new HttpEntity<>(reqpayload , headers);
        /**
         * exchange( urltobehit, httpmethod, header, response, urivaraibles
         * we are sending get request and expecting boolean response
         */
        ResponseEntity<Boolean> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Boolean.class);
        if (response.getStatusCodeValue() == HttpStatus.OK.value()) {
            /**
             * Printing Resoponse body
             */
            System.out.println("test makes call successful :: " + response.getBody());
        } else {
            System.err.println("Error while test making call");
        }
    } catch (HttpStatusCodeException exception) {
        /**
         * to get status code for exception
         */
        System.err.println(exception);
    } catch (Exception e) {
        /**
         * Other exception
         */
        System.err.println(e);
    }
}

Here is brief explnation

here we are passing the request payload by passing the map, request boy is built

        HashMap<String, String> reqpayload = new HashMap<String, String>();
        reqpayload.put("user", "john");

Adding headers

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

Combining headers and body

        HttpEntity<?> httpEntity = new HttpEntity<>(reqpayload , headers);

Triggering a post call with request body and expected response as boolean

        ResponseEntity<Boolean> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Boolean.class);

following method accepts the data and reads the same

@PostMapping("simplepost")
@CrossOrigin
public boolean simplepost(@RequestBody Map<String,String> req) {
    System.out.println("Get request body and reading json body with key user :: "+req.get("user"));
    return true;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.