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

介绍

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

先决条件

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

考虑部署至本地的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 – for multiple params

从表格中计算参数

登录页面的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>
  • The method is POST.
  • The action is home.localhost:8080/SpringMVCExample/home
  • userName is of type text.

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

localhost:8080/SpringMVCExample/home?userName=Pankaj

这将作为HttpURLConnection示例的基础。

HttpURLConnection示例

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

    1. 从GET或POST URL字符串中创建URL对象。

 

    1. 在URL对象上调用openConnection()方法,返回一个HttpURLConnection实例。

 

    1. 在HttpURLConnection实例中设置请求方法(默认值为GET)。

 

    1. 在HttpURLConnection实例上调用setRequestProperty()方法,设置请求头的值(如”User-Agent”、”Accept-Language”等)。

 

    1. 我们可以调用getResponseCode()来获取响应的HTTP代码。这样,我们就知道请求是否被成功处理,或者是否有任何HTTP错误消息被抛出。

 

    1. 对于GET请求,使用Reader和InputStream来读取响应并相应处理。

 

    对于POST请求,在代码处理响应之前,需要从HttpURLConnection实例中获取OutputStream,并将POST参数写入其中。

下面是一个使用HttpURLConnection发送Java GET和POST请求的示例程序。

HttpURLConnectionExample.java的示例
package com.scdev.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.");
		}
	}

}

编译并运行代码,将产生以下输出:

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协议发送GET和POST请求,那么你需要使用javax.net.ssl.HttpsURLConnection而不是java.net.HttpURLConnection。HttpsURLConnection会处理SSL握手和加密。

结论

在本文中,您学习了如何在Java程序中使用HttpURLConnection发送GET和POST请求,并打印出响应。

继续通过更多的Java教程来提高你的学习。

发表回复 0

Your email address will not be published. Required fields are marked *


广告
将在 10 秒后关闭
bannerAds