Skip to content

Instantly share code, notes, and snippets.

@yidas
Last active April 24, 2024 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yidas/869251ced36e910d1d0b0b7a74c44590 to your computer and use it in GitHub Desktop.
Save yidas/869251ced36e910d1d0b0b7a74c44590 to your computer and use it in GitHub Desktop.
JAVA HTTP Client Sample codes

JAVA HTTP Client Sample codes

HttpURLConnection

/**
 * @see https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html
 * @see https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html
 * @see https://www.baeldung.com/java-http-request
 * @see https://www.baeldung.com/httpurlconnection-post
 */

import java.net.*;
import java.io.*;

public class HttpClient {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://example.com");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            //			con.setRequestMethod("POST");
            //			con.setRequestProperty("Content-Type", "application/json");
            //			con.setConnectTimeout(5000);
            //			con.setReadTimeout(20000);

            // Send RequestBody Option
            con.setDoOutput(true);
            con.setRequestProperty("Content-Type", "application/json");
            String jsonInputString = "{\"key\": \"value\", \"number\": 42, \"flag\": true}";
            try(OutputStream os = con.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // Read the Response From Input Stream
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            con.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
            in.close();

        } catch (MalformedURLException e) {
            System.out.println("The specified URL is malformed: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("An I/O error occurs: " + e.getMessage());
        }
    }
}

Apache HttpClient

Apache HttpComponents

version: 4.x

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.http.conn.ConnectTimeoutException;
import java.net.SocketTimeoutException;
import java.io.IOException;

public class ApacheHttpClient {
    public static void main(String[] args) {
        RequestConfig config = RequestConfig.custom()
            // .setConnectTimeout(5000)
            // .setConnectionRequestTimeout(5000)
            // .setSocketTimeout(20000)
            .build();

        try (final CloseableHttpClient httpclient =
            HttpClientBuilder.create().setDefaultRequestConfig(config).build()) {
            final HttpGet httpget = new HttpGet("http://www.yidas.com");

            // System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getURI());

            CloseableHttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity);

            System.out.println(responseBody);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } catch (ConnectTimeoutException e) {
            // Handle connect timeout
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            // Handle read timeout
            e.printStackTrace();
        }
    }
}

Spring RestTemplate

Package org.springframework.boot:spring-boot-starter-web

This HTTP client is based on Apache HttpClient

import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class SpringHttpClient {
	public static void main(String[] args) {
		final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
		requestFactory.setConnectTimeout(000);
		RestTemplate restTemplate=new RestTemplate(requestFactory);
		String responseBody = restTemplate.getForObject("http://dns.yidas.com", String.class);
		System.out.println(responseBody);
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment