如何将 Java HttpURLConnection 用于 HTTP GET 和 POST 请求

介绍

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

前提条件

对于这个HttpURLConnection示例,你应该已经完成了春季MVC教程(社区/教程/春季mvc教程),因为它有GETPOSTHTTP方法的URL。

考虑部署到一个本地主机的Tomcat服务器。

春天总结

Java HTTP GET 请求

  • localhost:8080/SpringMVCExample/

Spring-MVC-HelloWorld

Java HTTP 请求登录页面

  • localhost:8080/SpringMVCExample/login

Spring-MVC-HelloWorld-GET

Java HTTP POST 请求

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

Spring-MVC-HelloWorld-POST

从形式中提取参数

登录页面的HTML包含以下形式:

 1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
 2<html>
 3<head>
 4<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5<title>Login Page</title>
 6</head>
 7<body>
 8<form action="home" method="post">
 9<input type="text" name="userName"><br>
10<input type="submit" value="Login">
11</form>
12</body>
13</html>

*「方法」為「POST」。 *「行動」為「主頁」。

  • 「localhost:8080/SpringMVCExample/home」 *「用戶名」為「文字」。

您可以构建一个POST请求到:

1localhost:8080/SpringMVCExample/home?userName=Pankaj

这将作为HttpURLConnection示例的基础。

「HttpURLConnection」示例

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

GETPOST URL 字符串中创建一个URL对象 2.在HttpURLConnection的实例中返回的 URL 对象上调用openConnection()方法 3.在HttpURLConnection实例中设置请求方法(默认值为GET) 4.在HttpURLConnection实例中调用setRequestProperty()方法以设置请求标题值(如User-AgentAccept-Language等)。 5.我们可以调用getResponseCode()来获取响应的 HTTP 代码。这样,我们

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

 1[label HttpURLConnectionExample.java]
 2package com.journaldev.utils;
 3
 4import java.io.BufferedReader;
 5import java.io.IOException;
 6import java.io.InputStreamReader;
 7import java.io.OutputStream;
 8import java.net.HttpURLConnection;
 9import java.net.URL;
10
11public class HttpURLConnectionExample {
12
13    private static final String USER_AGENT = "Mozilla/5.0";
14
15    private static final String GET_URL = "https://localhost:9090/SpringMVCExample";
16
17    private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";
18
19    private static final String POST_PARAMS = "userName=Pankaj";
20
21    public static void main(String[] args) throws IOException {
22    	sendGET();
23    	System.out.println("GET DONE");
24    	sendPOST();
25    	System.out.println("POST DONE");
26    }
27
28    private static void sendGET() throws IOException {
29    	URL obj = new URL(GET_URL);
30    	HttpURLConnection con = (HttpURLConnection) obj.openConnection();
31    	con.setRequestMethod("GET");
32    	con.setRequestProperty("User-Agent", USER_AGENT);
33    	int responseCode = con.getResponseCode();
34    	System.out.println("GET Response Code :: " + responseCode);
35    	if (responseCode == HttpURLConnection.HTTP_OK) { // success
36    		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
37    		String inputLine;
38    		StringBuffer response = new StringBuffer();
39
40    		while ((inputLine = in.readLine()) != null) {
41    			response.append(inputLine);
42    		}
43    		in.close();
44
45    		// print result
46    		System.out.println(response.toString());
47    	} else {
48    		System.out.println("GET request did not work.");
49    	}
50
51    }
52
53    private static void sendPOST() throws IOException {
54    	URL obj = new URL(POST_URL);
55    	HttpURLConnection con = (HttpURLConnection) obj.openConnection();
56    	con.setRequestMethod("POST");
57    	con.setRequestProperty("User-Agent", USER_AGENT);
58
59    	// For POST only - START
60    	con.setDoOutput(true);
61    	OutputStream os = con.getOutputStream();
62    	os.write(POST_PARAMS.getBytes());
63    	os.flush();
64    	os.close();
65    	// For POST only - END
66
67    	int responseCode = con.getResponseCode();
68    	System.out.println("POST Response Code :: " + responseCode);
69
70    	if (responseCode == HttpURLConnection.HTTP_OK) { //success
71    		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
72    		String inputLine;
73    		StringBuffer response = new StringBuffer();
74
75    		while ((inputLine = in.readLine()) != null) {
76    			response.append(inputLine);
77    		}
78    		in.close();
79
80    		// print result
81    		System.out.println(response.toString());
82    	} else {
83    		System.out.println("POST request did not work.");
84    	}
85    }
86
87}

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

1[secondary_label Output]
2GET Response Code :: 200
3<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>
4GET DONE
5POST Response Code :: 200
6<!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>
7POST DONE

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

如果你必须通过HTTPS协议发送GETPOST请求,那么你需要使用javax.net.ssl.HttpsURLConnection而不是java.net.HttpURLConnection

结论

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

继续学习更多的Java教程(https://andsky.com/tags/java)。

Published At
Categories with 技术
Tagged with
comments powered by Disqus