介绍
来自java.net
包的HttpURLConnection
类可用于以编程方式发送Java HTTP请求。在本文中,您将学习如何在Java程序中使用HttpURLConnection
来发送GET
和POST
请求,然后打印响应。
先决条件
对于这个HttpURLConnection
示例,您应该已经完成了Spring MVC教程,因为它具有GET
和POST
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>
method
是POST
。action
是home
。localhost:8080/SpringMVCExample/home
userName
的类型是text
。
你可以构造一个POST
请求到:
localhost:8080/SpringMVCExample/home?userName=Pankaj
这将作为HttpURLConnection
示例的基础。
HttpURLConnection
示例
以下是使用HttpURLConnection
类发送Java HTTP请求的步骤:
- 从
GET
或POST
URL字符串创建一个URL
对象。 - 在URL对象上调用
openConnection()
方法,返回一个HttpURLConnection
实例。 - 设置
HttpURLConnection
实例中的请求方法(默认值为GET
)。 - 在
HttpURLConnection
实例上调用setRequestProperty()
方法,设置请求头值(例如"User-Agent"
、"Accept-Language"
等)。 - 我们可以调用
getResponseCode()
来获取响应的HTTP状态码。这样,我们就知道请求是否成功处理,或者是否有任何HTTP错误消息抛出。 - 对于
GET
,使用Reader
和InputStream
来读取响应并相应地处理它。 - 对于
POST
,在代码处理响应之前,它需要从HttpURLConnection
实例中获取OutputStream
并将POST
参数写入其中。
以下是使用HttpURLConnection
发送Java GET
和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) { // 成功
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.");
}
}
}
编译并运行代码。它将生成以下输出:
OutputGET 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教程。