Get request data java

How To Make HTTP GET/POST Request in Java

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.

The common example of HTTP usage in real life is the connection between a web browser and server(s) for browsing. A client (web browser) submits an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.

HTTP is perhaps the most significant protocol used on the Internet today. Web services, network-enabled appliances and the growth of network computing continue to expand the role of the HTTP protocol beyond user-driven web browsers, while increasing the number of applications that require HTTP support.

The two most common HTTP methods are GET and POST.

HTTP GET

GET is used to request data from a specified resource. GET requests are only used to request data (not modify)

HTTP POST

POST is used to send data to a server to create/update a resource. The data sent to the server with POST is enclosed in the request body of the HTTP request. It is often used when uploading a file or when submitting a completed web form.

For the list of most common HTTP Methods, please refer to HTTP Methods in Spring RESTful Services.

In this article, we will check different classes or libraries to make HTTP GET/POST requests in Java. The examples will be using onlinefreeconverter.com for testing. The examples also will guide on how to make HTTPS connection.

Читайте также:  Название документа

HttpsURLConnection

HttpURLConnection class is an abstract class extends from URLConnection class. It includes all the functionality of URLConnection with additional HTTP specific features. Using HttpURLConnection class, we can get information of an HTTP connection such as header information, status code, response code, etc.

HttpsURLConnection extends HttpURLConnection with support for https-specific features.

package com.dariawan.http; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import java.nio.charset.StandardCharsets; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class HttpsURLConnectionExample < private HttpsURLConnection getHttpsClient(String url) throws Exception < // Security section START TrustManager[] trustAllCerts = new TrustManager[]< new X509TrustManager() < @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() < return null; >@Override public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) < >@Override public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) < >>>; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Security section END HttpsURLConnection client = (HttpsURLConnection) new URL(url).openConnection(); //add request header client.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"); return client; > private void testGet() throws Exception < System.out.println("*** Test Http GET request ***"); String url = "https://www.onlinefreeconverter.com/random-words?n=15"; HttpsURLConnection client = getHttpsClient(url); int responseCode = client.getResponseCode(); System.out.println("GET request to URL: " + url); System.out.println("Response Code : " + responseCode); try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()))) < StringBuilder response = new StringBuilder(); String line; while ((line = in.readLine()) != null) < response.append(line).append("\n"); >System.out.println(response.toString()); > > private void testPost() throws Exception < System.out.println("*** Test Http POST request ***"); String url = "https://www.onlinefreeconverter.com/test/post"; String urlParameters = "param1=a&param2=b&param3=c"; byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpsURLConnection client = getHttpsClient(url); client.setRequestMethod("POST"); client.setDoOutput(true); client.setInstanceFollowRedirects(false); client.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); client.setRequestProperty("charset", "utf-8"); client.setRequestProperty("Content-Length", Integer.toString(postDataLength)); client.setUseCaches(false); try (OutputStream os = client.getOutputStream()) < os.write(postData); >int responseCode = client.getResponseCode(); System.out.println("POST request to URL: " + url); System.out.println("POST Parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()))) < String line; StringBuilder response = new StringBuilder(); while ((line = in.readLine()) != null) < response.append(line).append("\n"); >System.out.println(response.toString()); > > public static void main(String[] args) throws Exception < HttpsURLConnectionExample obj = new HttpsURLConnectionExample(); obj.testGet(); obj.testPost(); >> 

Apache HttpClient

Before Java 11, most of us will use HttpComponents Client from Apache instead of HttpURLConnection or HttpsURLConnection . The following example uses Apache HttpClient to create GET/POST request. If your project using maven, you may need to add an additional dependency:

org.apache.httpcomponents httpclient 4.5.6
package com.dariawan.http; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class ApacheHttpClientExample < private final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"; private HttpClient getHttpClient() throws Exception < RequestConfig.Builder requestBuilder = RequestConfig.custom(); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setDefaultRequestConfig(requestBuilder.build()); builder.setSSLSocketFactory(SSLUtil.getInsecureSSLConnectionSocketFactory()); HttpClient httpClient = builder.build(); return httpClient; >private void testGet() throws Exception < System.out.println("*** Test Http GET request ***"); String url = "https://www.onlinefreeconverter.com/random-words?n=15"; HttpGet request = new HttpGet(url); // add request headers request.addHeader(HttpHeaders.USER_AGENT, USER_AGENT); HttpClient client = getHttpClient(); HttpResponse response = client.execute(request); System.out.println("GET request to URL: " + url); System.out.println("Response Status : " + response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); System.out.println(result); >private void testPost() throws Exception < System.out.println("*** Test Http POST request ***"); String url = "https://www.onlinefreeconverter.com/test/post"; HttpPost request = new HttpPost(url); // String urlParameters = "param1=a&param2=b&param3=c"; ListurlParameters = new ArrayList<>(); urlParameters.add(new BasicNameValuePair("param1", "a")); urlParameters.add(new BasicNameValuePair("param2", "b")); urlParameters.add(new BasicNameValuePair("param3", "c")); request.setEntity(new UrlEncodedFormEntity(urlParameters)); request.addHeader(HttpHeaders.USER_AGENT, USER_AGENT); request.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); // request.addHeader("charset", "utf-8"); HttpClient client = getHttpClient(); HttpResponse response = client.execute(request); System.out.println("POST request to URL: " + url); System.out.println("POST Parameters : " + urlParameters.toString()); System.out.println("Response Status : " + response.getStatusLine().toString()); System.out.println(EntityUtils.toString(response.getEntity())); > public static void main(String[] args) throws Exception < ApacheHttpClientExample obj = new ApacheHttpClientExample(); obj.testGet(); obj.testPost(); >private static class SSLUtil < protected static SSLConnectionSocketFactory getInsecureSSLConnectionSocketFactory() throws KeyManagementException, NoSuchAlgorithmException < final TrustManager[] trustAllCerts = new TrustManager[]< new X509TrustManager() < @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() < return null; >@Override public void checkClientTrusted( final java.security.cert.X509Certificate[] arg0, final String arg1) throws CertificateException < // do nothing and blindly accept the certificate >@Override public void checkServerTrusted( final java.security.cert.X509Certificate[] arg0, final String arg1) throws CertificateException < // do nothing and blindly accept the server >> >; final SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, trustAllCerts, new java.security.SecureRandom()); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[], null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); return sslsf; > > > 

Java 11 HttpClient

From Java 11, the HTTP Client API is now part of the Java SE 11 standard. The module name and the package name of the standard API is java.net.http. The new APIs provide high-level client interfaces to HTTP (versions 1.1 and 2) and low-level client interfaces to WebSocket.

package com.dariawan.http; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class HttpClientExample < private final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"; private HttpClient getHttpClient() < return HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .build(); >private void testGet() throws Exception < System.out.println("*** Test Http GET request ***"); String url = "https://www.onlinefreeconverter.com/random-words?n=15"; HttpRequest request = HttpRequest.newBuilder() .GET() .uri(URI.create(url)) .setHeader("User-Agent", USER_AGENT) // request header .build(); HttpResponseresponse = getHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("GET request to URL: " + url); System.out.println("Response Code : " + response.statusCode()); System.out.println(response.body()); > private void testPost() throws Exception < System.out.println("*** Test Http POST request ***"); String url = "https://www.onlinefreeconverter.com/test/post"; String urlParameters = "param1=a&param2=b&param3=c"; HttpRequest request = HttpRequest.newBuilder() .POST(HttpRequest.BodyPublishers.ofString(urlParameters)) .uri(URI.create(url)) .setHeader("User-Agent", USER_AGENT) // request header .header("Content-Type", "application/x-www-form-urlencoded") .build(); HttpResponseresponse = getHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("POST request to URL: " + url); System.out.println("Post Parameters : " + urlParameters); System.out.println("Response Code : " + response.statusCode()); System.out.println(response.body()); > public static void main(String[] args) throws Exception < HttpClientExample obj = new HttpClientExample(); obj.testGet(); obj.testPost(); >> 

Using Java 11 HttpClient API, we not encounter problem with SSL certificates when making HTTPS Connection.

If you are already using Java 11, it’s recommended to use (or upgrade to) this library. The reason are:

  • Java 11 HttpClient is easier to use, and more flexible. Although part of standard library, HttpURLConnection and HttpsURLConnection are considered outdated.
  • No extra dependency needed, compared to Apache HttpClient. I also made one comparison between those two in this article.

Liked this Tutorial? Share it on Social media!

Источник

Оцените статью