如何使用Java HttpURLConnection进行HTTP GET和POST请求

介绍

来自java.net包的HttpURLConnection类可用于以编程方式发送Java HTTP请求。在本文中,您将学习如何在Java程序中使用HttpURLConnection来发送GETPOST请求,然后打印响应。

先决条件

对于这个HttpURLConnection示例,您应该已经完成了Spring MVC教程,因为它具有GETPOST HTTP方法的URL。

考虑部署到localhost Tomcat服务器。

SpringMVCExample摘要

Java HTTP GET请求

  • localhost:8080/SpringMVCExample/

用于登录页面的Java HTTP GET请求

  • localhost:8080/SpringMVCExample/login

Java HTTP POST请求

  • localhost:8080/SpringMVCExample?userName=Pankaj
  • localhost:8080/SpringMVCExample/login?userName=Pankaj&pwd=apple123 – 用于多个参数

从表单中获取参数

登录页面的HTML包含以下表单:

<!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>
  • methodPOST
  • actionhome
    • localhost:8080/SpringMVCExample/home
  • userName的类型是text

你可以构造一个POST请求到:

localhost:8080/SpringMVCExample/home?userName=Pankaj

这将作为HttpURLConnection示例的基础。

HttpURLConnection示例

以下是使用HttpURLConnection类发送Java HTTP请求的步骤:

  1. GETPOST URL字符串创建一个URL对象。
  2. 在URL对象上调用openConnection()方法,返回一个HttpURLConnection实例。
  3. 设置HttpURLConnection实例中的请求方法(默认值为GET)。
  4. HttpURLConnection实例上调用setRequestProperty()方法,设置请求头值(例如"User-Agent""Accept-Language"等)。
  5. 我们可以调用getResponseCode()来获取响应的HTTP状态码。这样,我们就知道请求是否成功处理,或者是否有任何HTTP错误消息抛出。
  6. 对于GET,使用ReaderInputStream来读取响应并相应地处理它。
  7. 对于POST,在代码处理响应之前,它需要从HttpURLConnection实例中获取OutputStream并将POST参数写入其中。

以下是使用HttpURLConnection发送Java GETPOST请求的示例程序:

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

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

			// 打印结果
			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);

		// 仅用于POST - 开始
		con.setDoOutput(true);
		OutputStream os = con.getOutputStream();
		os.write(POST_PARAMS.getBytes());
		os.flush();
		os.close();
		// 仅用于POST - 结束

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

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

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

			// 打印结果
			System.out.println(response.toString());
		} else {
			System.out.println("POST request did not work.");
		}
	}

}

编译并运行代码。它将生成以下输出:

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

将此输出与浏览器HTTP响应进行比较。

如果您需要通过HTTPS协议发送GETPOST请求,那么您需要使用javax.net.ssl.HttpsURLConnection而不是java.net.HttpURLConnectionHttpsURLConnection将处理SSL握手和加密。

结论

在本文中,您学习了如何在Java程序中使用HttpURLConnection发送GETPOST请求,然后打印响应。

继续学习更多Java教程

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