Apache HttpClient - Http Post Request

Uma solicitação POST é usada para enviar dados ao servidor; por exemplo, informações do cliente, upload de arquivo, etc., usando formulários HTML.

A API HttpClient fornece uma classe chamada HttpPost que representa a solicitação POST.

Siga as etapas fornecidas abaixo para enviar uma solicitação HTTP POST usando a biblioteca HttpClient.

Etapa 1 - Criar um objeto HttpClient

o createDefault() método do HttpClients classe retorna um objeto da classe CloseableHttpClient, que é a implementação básica do HttpClient interface.

Usando esse método, crie um objeto HttpClient.

CloseableHttpClient httpClient = HttpClients.createDefault();

Etapa 2 - Criar objeto HttpPost

o HttpPost classe representa o HTTP POSTsolicitação. Isso envia os dados necessários e recupera as informações do servidor fornecido usando um URI.

Crie esta solicitação instanciando o HttpPost classe e passa um valor de string representando o URI, como um parâmetro para seu construtor.

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

Etapa 3 - Executar a solicitação Get

o execute() O método do objeto CloseableHttpClient aceita um objeto HttpUriRequest (interface) (isto é, HttpGet, HttpPost, HttpPut, HttpHead etc.) e retorna um objeto de resposta.

HttpResponse httpResponse = httpclient.execute(httpget);

Exemplo

A seguir está um exemplo que demonstra a execução da solicitação HTTP POST usando a biblioteca HttpClient.

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

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

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

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

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

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

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

Resultado

O programa acima gera a seguinte saída.

Request Type: POST
<!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" conten t= "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>