Home

Создание запроса с помощью HttpRequest

Класс HttpRequеst используется для описания http-request, что легко понять из его названия. Этот объект сам по себе ничего не делает, он только содержит разнообразную информацию по поводу http-запроса. Поэтому, как ты уже, наверное, догадываешься, для его создания тоже используется шаблон Builder.

 HttpRequest request = HttpRequest.newBuilder() .method1() .method2() .methodN() .build(); 

Где между вызовами методов newBuilder() и build() нужно вызвать все методы для конструирования объекта HttpRequest .

Пример простейшего запроса выглядит так:

 HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(“http://javarush.com”)) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); 

Все методы класса HttpRequest ты можешь найти по ссылке в официальной документации.

А дальше мы разберем самые популярные из них.

Метод uri()

С помощью метода uri() можно задать URI (или URL), к которому будет отправлен http-запрос. Пример:

 HttpRequest request = HttpRequest.newBuilder() .uri( URI.create(“http://javarush.com”) ) .build(); 

Кстати, можно записать этот код еще немного короче, передав URI прямо в метод newBuilder() :

 HttpRequest request = HttpRequest.newBuilder( URI.create(“http://javarush.com”) ).build(); 

Важно! URI можно создать двумя способами:

Второй способ предпочтительнее. Первый способ, к сожалению, не очень хорош, потому-то конструктор URI объявлен так public URI(String str) throws URISyntaxException , а URISyntaxException — это checked-исключение.

Методы GET(), POST(), PUT(), DELETE()

Задать http-метод запроса можно с помощью методов:

Вот как будет выглядеть простой GET-запрос:

 HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://javarush.com")) .GET() .build(); 

Метод version()

Также можно задать версию HTTP-протокола. Их всего 2 варианта:

Допустим, ты хочешь создать запрос по протоколу HTTP/2, тогда тебе нужно будет написать:

 HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://javarush.com")) .version( HttpClient.Version.HTTP_2 ) .GET() .build(); 

Очень просто, не правда ли? 🙂

Метод timeout()

Также можно задать время выполнения запроса. Если оно пройдет, а запрос так и не будет выполнен, то выкинется исключение HttpTimeoutException .

Само время задается с помощью объекта Duration из Java DateTime API. Пример:

 HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://javarush.com")) .timeout( Duration.of(5, SECONDS) ) .GET() .build(); 

Наличие этого метода показывает, что классы HttpClient и HttpRequest могут решать самые разнообразные задачи. Представь, что ты выполняешь запрос, а что-то случилось с сетью и он продлился 30 секунд. Куда полезнее сразу получить исключение и правильно на него среагировать.

Метод header()

Также к любому запросу можно добавить сколько угодно заголовков. И сделать это так же просто, как и все остальное. Для этого есть специальный метод — header() . Пример:

 HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://javarush.com")) .header("name1", "value1") .header("name2", "value2") .GET() .build(); 

Есть еще один альтернативный способ задать сразу много заголовков. Может пригодиться, если, ты, допустим, преобразовал список заголовков в массив:

 HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://javarush.com")) .headers("name1", "value1", "name2", "value2") .GET() .build(); 

Источник

How To Use Java HttpURLConnection for HTTP GET and POST Requests

How To Use Java HttpURLConnection for HTTP GET and POST Requests

The HttpURLConnection class from java.net package can be used to send a Java HTTP Request programmatically. In this article, you will learn how to use HttpURLConnection in a Java program to send GET and POST requests and then print the response.

Prerequisites

For this HttpURLConnection example, you should have completed the Spring MVC Tutorial because it has URLs for GET and POST HTTP methods.

Consider deploying to a localhost Tomcat server.

SpringMVCExample Summary

Java HTTP GET Request

Spring-MVC-HelloWorld

Java HTTP GET Request for Login Page

Spring-MVC-HelloWorld-GET

Java HTTP POST Request

  • localhost:8080/SpringMVCExample?userName=Pankaj
  • localhost:8080/SpringMVCExample/login?userName=Pankaj&pwd=apple123 — for multiple params

Spring-MVC-HelloWorld-POST

Deriving parameters from the form

The HTML of the login page contains the following form:

DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"> html> head> meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> title>Login Pagetitle> head> body> form action="home" method="post"> input type="text" name="userName">br> input type="submit" value="Login"> form> body> html> 

You can construct a POST request to:

localhost:8080/SpringMVCExample/home?userName=Pankaj 

This will serve as the basis for the HttpURLConnection example.

HttpURLConnection Example

Here are the steps for sending Java HTTP requests using HttpURLConnection class:

  1. Create a URL object from the GET or POST URL String.
  2. Call the openConnection() method on the URL object that returns an instance of HttpURLConnection .
  3. Set the request method in HttpURLConnection instance (default value is GET ).
  4. Call setRequestProperty() method on HttpURLConnection instance to set request header values (such as «User-Agent» , «Accept-Language» , etc).
  5. We can call getResponseCode() to get the response HTTP code. This way, we know if the request was processed successfully or if there was any HTTP error message thrown.
  6. For GET , use Reader and InputStream to read the response and process it accordingly.
  7. For POST , before the code handles the response, it needs to get the OutputStream from the HttpURLConnection instance and write POST parameters into it.

Here is an example program that uses HttpURLConnection to send Java GET and POST requests:

package com.journaldev.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionExample  private static final String USER_AGENT = "Mozilla/5.0"; private static final String GET_URL = "https://localhost:9090/SpringMVCExample"; private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home"; private static final String POST_PARAMS = "userName=Pankaj"; public static void main(String[] args) throws IOException  sendGET(); System.out.println("GET DONE"); sendPOST(); System.out.println("POST DONE"); > private static void sendGET() throws IOException  URL obj = new URL(GET_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("GET Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK)  // success BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null)  response.append(inputLine); > in.close(); // print result System.out.println(response.toString()); > else  System.out.println("GET request did not work."); > > private static void sendPOST() throws IOException  URL obj = new URL(POST_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); // For POST only - START con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(POST_PARAMS.getBytes()); os.flush(); os.close(); // For POST only - END int responseCode = con.getResponseCode(); System.out.println("POST Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK)  //success BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null)  response.append(inputLine); > in.close(); // print result System.out.println(response.toString()); > else  System.out.println("POST request did not work."); > > > 

Compile and run the code. It will produce the following output:

Output
GET Response Code :: 200

Hello world!

The time on the server is March 6, 2015 9:31:04 PM IST.

GET DONE POST Response Code :: 200

Hi Pankaj

POST DONE

Compare this output to the browser HTTP response.

If you have to send GET and POST requests over HTTPS protocol, then you need to use javax.net.ssl.HttpsURLConnection instead of java.net.HttpURLConnection . HttpsURLConnection will handle the SSL handshake and encryption.

Conclusion

In this article, you learned how to use HttpURLConnection in a Java program to send GET and POST requests and then print the response.

Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Читайте также:  Javascript проверить что переменная объект
Оцените статью