Apache HttpClient - Http Get Request

El método GET se usa para recuperar información del servidor dado usando un URI dado. Las solicitudes que utilizan GET solo deben recuperar datos y no deben tener ningún otro efecto sobre los datos.

La API de HttpClient proporciona una clase denominada HttpGet que representa el método de solicitud de obtención.

Siga los pasos que se indican a continuación para enviar una solicitud de obtención utilizando la biblioteca HttpClient

Paso 1: crea un objeto HttpClient

los createDefault() método del HttpClients la clase devuelve un CloseableHttpClient objeto, que es la implementación base del HttpClient interfaz.

Con este método, cree un objeto HttpClient como se muestra a continuación:

CloseableHttpClient httpclient = HttpClients.createDefault();

Paso 2: crear un objeto HttpGet

los HttpGet class representa la solicitud HTTPGET que recupera la información del servidor dado usando un URI.

Cree una solicitud HTTP GET creando una instancia de esta clase. El constructor de esta clase acepta un valor de cadena que representa el URI.

HttpGet httpget = new HttpGet("http://www.tutorialspoint.com/");

Paso 3: ejecutar la solicitud de obtención

los execute() método del CloseableHttpClient La clase acepta un objeto HttpUriRequest (interfaz) (es decir, HttpGet, HttpPost, HttpPut, HttpHead, etc.) y devuelve un objeto de respuesta.

Ejecute la solicitud utilizando este método como se muestra a continuación:

HttpResponse httpresponse = httpclient.execute(httpget);

Ejemplo

A continuación se muestra un ejemplo que demuestra la ejecución de la solicitud HTTP GET utilizando la biblioteca HttpClient.

import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpGetExample {
 
   public static void main(String args[]) throws Exception{
 
      //Creating a HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

      //Creating a HttpGet object
      HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/ ");

      //Printing the method used
      System.out.println("Request Type: "+httpget.getMethod());

      //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httpget);

      Scanner sc = new Scanner(httpresponse.getEntity().getContent());

      //Printing the status line
      System.out.println(httpresponse.getStatusLine());
      while(sc.hasNext()) {
         System.out.println(sc.nextLine());
      }
   }
}

Salida

El programa anterior genera la siguiente salida:

Request Type: GET
<!DOCTYPE html>
<!--[if IE 8]><html class = "ie ie8"> <![endif]-->
<!--[if IE 9]><html class = "ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang = "en-US"> <!--<![endif]-->
<head>
<!-- Basic -->
<meta charset = "utf-8">
<title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java
i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible,
LOLCODE, Current Affairs 2018, Apache Commons Collections</title>
<meta name = "Description" content = "Parallax Scrolling, Java Cryptography, YAML,
Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common
CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache
Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC),
Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow"/>
<meta name = "Keywords" content = "Python Data Science, Java i18n, GitLab,
TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson,
TestLink, Inter Process Communication (IPC), Logo"/>
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes">
<link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css"
rel = "stylesheet" type = "text/css" />
<link rel = "stylesheet" href="/questions/css/home.css?v = 3" />
<script src = "/questions/js/jquery.min.js"></script>
<script src = "/questions/js/fontawesome.js"></script>
<script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script>
</head>
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
</script>
</body>
</html>