What is http request and response in java

Request HTTP Client and Get Response in Java

Request HTTP Client and Get Response in Java

  1. Send an HTTP Request and Receive a JSON Response From Client in Java
  2. Execute HTTP Request and Get Response Asynchronously in Java

We will use an HTTP Client in Java to send requests and receive responses. Meanwhile, you will also learn how to use the body handlers, builder, and other underlying methods to send an HTTP Client request.

Send an HTTP Request and Receive a JSON Response From Client in Java

We will use a demo JSON website that programmers use to evaluate their HTTP requests. Here it is https://blog.typicode.com/ .

  1. HttpClient send2client = HttpClient.newHttpClient(); — We use it to send http requests to clients and receive responses.
  2. HttpRequest Req2client = HttpRequest(); — This method helps build http request as an instance with its following parameters.
    2.1 .newBuilder(); — Generates an Http Request builder. This method returns a builder that builds the standard HTTP Client API objects.
    2.2 .uri(«The Client URL»); — Sets http request’s URL.
    2.3 .build(); — This parameter builds and returns http request.
  3. HttpResponse clientRes = send2client.send(Req2client, HttpResponse.BodyHandlers.ofString()); — The response status code, headers, response body, and the HTTP Request corresponding to this response are all accessible through this class.

Check out the following program that performs everything that we discussed so far.

import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse;  public class Example1   public static void main(String[] args) throws IOException, InterruptedException   HttpClient send2client = HttpClient.newHttpClient();  HttpRequest Req2client = HttpRequest.newBuilder().uri(URI.create("https://blog.typicode.com/")).build();  String format = System.getProperty("line.separator");  HttpResponseString> clientRes = send2client.send(Req2client, HttpResponse.BodyHandlers.ofString());  System.out.println(" Requested Responses from the client" + format + "1: Status code" + format+ clientRes.statusCode() + format);  System.out.println("2: Uniform Resource Locator (URL) from the client" + clientRes.uri() + format);  System.out.println("3: SSL Session" + format + clientRes.sslSession() + format);  System.out.println("4: HTTP version" + format + clientRes.version() + format);  //System.out.println("5: Response Header" + format + clientRes.headers() + format);  //System.out.println("6: Response Body" + format + clientRes.body() + format);   > > 
Requested Responses from the client 1: Status code 200 2: Uniform Resource Locator (URL) from the client: https://blog.typicode.com/ 3: SSL Session Optional[jdk.internal.net.http.common.ImmutableExtendedSSLSession@5bcea91b] 4: HTTP version HTTP_2 

Execute HTTP Request and Get Response Asynchronously in Java

We will use the same HttpRequest method in the following code block but with the following functions.

sendAsync() — This client sends the specified request asynchronously with the specified response body handlers.

The sendAsync() and HttpRequest are sending and retrieving methods. Both are secure for HTTP web handlers.

Cli.sendAsync(RQI, BodyHandlers.ofString())  .thenApply(HttpResponse::body) //optional  .thenAccept(System.out::println) //The action to take before completing the retrieved completion stage  .join(); //returts the response value 
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers;  public class Example2   public static void main(String[] args)   HttpClient Cli = HttpClient.newHttpClient();  HttpRequest RQI = HttpRequest.newBuilder()  .uri(URI.create("https://www.delftstack.com"))  .build();  Cli.sendAsync(RQI, BodyHandlers.ofString())  .thenApply(HttpResponse::body)  .thenAccept(System.out::println)  .join();  > > 

Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.

Related Article — Java HTTP

Источник

How to Create an HTTP Client in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Java Programming tutorials

The Internet consists of thousands of web applications that communicate with each other everyday. These applications usually communicate via HTTP (HyperText Transfer Protocol). HTTP is an application layer protocol that enables web applications to transfer data between each other (ie; communicate). HTTP generally follows a client-server architecture. The client initiates the communication with a server by sending an HTTP request. The server then responds with an HTTP response.

In this programming tutorial, developers will learn how to create a simple HTTP Java client to communicate with an HTTP server using the Java programming language.

What are HTTP Messages in Java?

In Java, there are two types of HTTP messages: requests and responses.

Java HTTP Requests

HTTP requests generally consist of four parts: a start line, HTTP header, a blank line, and the body. The start line and HTTP header are collectively known as the head.

Start Line

The start line in an HTTP request specifies the HTTP method, request target (URL to be accessed), and the HTTP version to be used during the communication. An HTTP method is a command (such as GET, POST, or HEAD) that defines how your client is going to interact with a given resource on a server.

There are currently two HTTP versions that you can use: 1.1 or 2. The default is HTTP/1.1.

HTTP header (optional)

The HTTP header is a header:value pair which can define certain properties that relate to the client or server. These properties can include things such as the user agent (browser in use), proxy, content type, or connection.

Body (also known as payload)

The body is optional, and it depends on the request type. For example, GET and DELETE request types do not need a body since they are not carrying any payload to the server. The payload is, ideally, a file being transferred.

Java HTTP Response

Java HTTP responses consist of three parts: status line, header, and a body.

  • Status Line: This consists of the HTTP protocol version, status code, and a status text. A status code is a number that describes the success or failure of the request. A status text is a short, human readable message that describes the status of the response.
  • Header: Headers are just like those described in HTTP requests.
  • Body: The body is optional, depending on the message type.

How to Use the Java HttpClient Class

Java provides the HttpClient Class, which programmers can use create a client. Here is the syntax for using HttpClient in Java:

HttpClient client = HttpClient.newHttpClient();

In the code example above, the newHttpClient() method allows developers to create an HTTP client with the default configurations.

Next, you need to use the newBuilder() method to build a request. At bare minimum, you need to provide the URI of your requested resource and the request method. The default is GET(). Therefore, if you do not indicate one, GET will be used.

HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://openjdk.org/groups/net/httpclient/recipes.html")) .GET() .build();

After creating your request, you need to send it and get a response:

HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());

The code example below shows how programmers can send a request to developer.com and then save it in an HTML file using Java and HttpClient:

import java.net.http.*; import java.net.*; import java.io.*; public class HttpClientApp < public static void main(String[] args) throws IOException, InterruptedException < HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://www.developer.com/")) .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); File fileObj = new File("developer.html"); fileObj.createNewFile(); FileWriter fileWriterObj = new FileWriter("developer.html"); fileWriterObj.write(response.body()); >>

You can open this file (developer.html) from your browser to see its contents.

Final Thoughts on Java HTTP Clients

The web is filled with many applications that use HTTP protocols. One good example is your web browser (the one you are using to access this site). Your web browser is an HTTP client that communicates with a web server that serves you a webpage. This Java programming tutorial showed how to build your own HTTP client in Java to access the contents of a web page.

Источник

Читайте также:  Python поверхность по точкам
Оцените статью