Como usar Java HttpURLConnection para solicitações HTTP GET e POST

Introdução

A classe HttpURLConnection do pacote java.net pode ser utilizada para enviar programaticamente uma requisição HTTP em Java. Neste artigo, você aprenderá como usar HttpURLConnection em um programa Java para enviar requisições GET e POST e então imprimir a resposta.

Pré-requisitos

Para este exemplo de HttpURLConnection, é necessário ter concluído o Tutorial do Spring MVC pois ele contém URLs para os métodos HTTP GET e POST.

Considere implantar em um servidor localhost Tomcat.

Resumo do SpringMVCExample

Requisição HTTP GET em Java

  • localhost:8080/SpringMVCExample/

Requisição HTTP GET em Java para a Página de Login

  • localhost:8080/SpringMVCExample/login

Requisição HTTP POST em Java

  • localhost:8080/SpringMVCExample?userName=Pankaj
  • localhost:8080/SpringMVCExample/login?userName=Pankaj&pwd=apple123 – para múltiplos parâmetros

Derivando parâmetros do formulário

O HTML da página de login contém o seguinte formulário:

<!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 Page</title>
</head>
<body>
<form action="home" method="post">
<input type="text" name="userName"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
  • O método é POST.
  • A ação é home.
    • localhost:8080/SpringMVCExample/home
  • userName é do tipo text.

Você pode construir uma requisição POST para:

localhost:8080/SpringMVCExample/home?userName=Pankaj

Isso servirá de base para o exemplo de HttpURLConnection.

Exemplo de HttpURLConnection

Aqui estão os passos para enviar requisições HTTP em Java usando a classe HttpURLConnection:

  1. Crie um objeto URL a partir da String de URL do GET ou POST.
  2. Chame o método openConnection() no objeto URL que retorna uma instância de HttpURLConnection.
  3. Defina o método de solicitação na instância de HttpURLConnection (o valor padrão é GET).
  4. Chame o método setRequestProperty() na instância de HttpURLConnection para definir os valores do cabeçalho da solicitação (como "User-Agent", "Accept-Language", etc).
  5. Podemos chamar getResponseCode() para obter o código HTTP de resposta. Dessa forma, sabemos se a solicitação foi processada com sucesso ou se houve algum erro HTTP lançado.
  6. Para GET, use Reader e InputStream para ler a resposta e processá-la adequadamente.
  7. Para POST, antes que o código manipule a resposta, ele precisa obter o OutputStream da instância de HttpURLConnection e escrever os parâmetros POST nele.

Aqui está um programa de exemplo que usa HttpURLConnection para enviar solicitações Java GET e POST:

HttpURLConnectionExample.java
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) { // sucesso
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			// imprimir resultado
			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);

		// Apenas para POST - INÍCIO
		con.setDoOutput(true);
		OutputStream os = con.getOutputStream();
		os.write(POST_PARAMS.getBytes());
		os.flush();
		os.close();
		// Apenas para POST - FIM

		int responseCode = con.getResponseCode();
		System.out.println("POST Response Code :: " + responseCode);

		if (responseCode == HttpURLConnection.HTTP_OK) { //sucesso
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			// imprimir resultado
			System.out.println(response.toString());
		} else {
			System.out.println("POST request did not work.");
		}
	}

}

Compile e execute o código. Ele produzirá a seguinte saída:

Output
GET Response Code :: 200 <html><head> <title>Home</title></head><body><h1> Hello world! </h1><P> The time on the server is March 6, 2015 9:31:04 PM IST. </P></body></html> GET DONE POST Response Code :: 200 <!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>User Home Page</title></head><body><h3>Hi Pankaj</h3></body></html> POST DONE

Compare esta saída com a resposta HTTP do navegador.

Se você precisa enviar solicitações GET e POST através do protocolo HTTPS, então você precisa usar javax.net.ssl.HttpsURLConnection em vez de java.net.HttpURLConnection. HttpsURLConnection lidará com o handshake SSL e a criptografia.

Conclusão

Neste artigo, você aprendeu como usar HttpURLConnection em um programa Java para enviar solicitações GET e POST e depois imprimir a resposta.

Continue sua aprendizagem com mais tutoriais de Java.

Source:
https://www.digitalocean.com/community/tutorials/java-httpurlconnection-example-java-http-request-get-post