HttpURLConnection class from java.net package can be used to send Java HTTP Request programmatically. Today we will learn how to use HttpURLConnection in java program to send GET and POST requests and then print the response.

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

Java HTTP请求 (Java HTTP Request)

For our HttpURLConnection example, I am using sample project from Spring MVC Tutorial because it has URLs for GET and POST HTTP methods. Below are the images for this web application, I have deployed it on my localhost tomcat server.

对于我们的HttpURLConnection示例,我正在使用Spring MVC教程中的示例项目,因为它具有GET和POST HTTP方法的URL。 下面是此Web应用程序的图像,我已将其部署在localhost tomcat服务器上。

Java HTTP GET Request

Java HTTP GET请求

Java HTTP GET Request for Login Page

Java HTTP GET登录页面请求

Java HTTP POST Request

Java HTTP POST请求

For Java HTTP GET requests, we have all the information in the browser URL itself. So from the above images, we know that we have the following GET request URLs.

对于Java HTTP GET请求,我们在浏览器URL本身中拥有所有信息。 因此,从以上图像中,我们知道我们具有以下GET请求URL。

  • https://localhost:9090/SpringMVCExample/https:// localhost:9090 / SpringMVCExample /
  • https://localhost:9090/SpringMVCExample/loginhttps:// localhost:9090 / SpringMVCExample /登录

Above URL’s don’t have any parameters but as we know that in HTTP GET requests parameters are part of URL itself, so for example if we have to send a parameter named userName with value as Pankaj then the URLs would have been like below.

上面的URL没有任何参数,但是众所周知,在HTTP GET请求中,参数本身就是URL的一部分,因此,例如,如果我们必须发送一个名为userName且值为Pankaj的参数,则这些URL将像下面这样。

  • https://localhost:9090/SpringMVCExample?userName=Pankajhttps:// localhost:9090 / SpringMVCExample?userName = Pankaj
  • https://localhost:9090/SpringMVCExample/login?userName=Pankaj&pwd=apple123 – for multiple paramshttps:// localhost:9090 / SpringMVCExample / login?userName = Pankaj&pwd = apple123 –用于多个参数

If we know the POST URL and what parameters it’s expecting, it’s awesome but in this case, we will figure it out from the login form source.

如果我们知道POST URL以及期望使用的参数,那么它很棒,但是在这种情况下,我们将从登录表单源中找出它。

Below is the HTML code we get when we view the source of the login page in any of the browsers.

下面是在任何浏览器中查看登录页面源代码时获得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>

Look at the form method in the source, as expected it’s POST method. Now see that action is “home”, so the POST URL would be https://localhost:9090/SpringMVCExample/home. Now check the different elements in the form, from the above form we can deduce that we need to send one POST parameter with name userName and it’s of type String.

查看源代码中的form方法,正如预期的那样是POST方法。 现在看到该操作为“ home”,因此POST URL为https:// localhost:9090 / SpringMVCExample / home 。 现在检查表单中的不同元素,从上面的表单中我们可以推断出我们需要发送一个名称为userName且类型为String的POST参数。

So now we have complete details of the GET and POST requests and we can proceed for the Java HTTP Request example program.

因此,现在我们已经完整了解了GET和POST请求,并且可以继续进行Java HTTP Request示例程序。

Below are the steps we need to follow for sending Java HTTP requests using HttpURLConnection class.

下面是使用HttpURLConnection类发送Java HTTP请求所需执行的步骤。

  1. Create URL object from the GET/POST URL String.从GET / POST URL字符串创建URL对象。
  2. Call openConnection() method on URL object that returns instance of HttpURLConnection在返回HttpURLConnection实例的URL对象上调用openConnection()方法
  3. Set the request method in HttpURLConnection instance, default value is GET.在HttpURLConnection实例中设置请求方法,默认值为GET。
  4. Call setRequestProperty() method on HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc.在HttpURLConnection实例上调用setRequestProperty()方法以设置请求标头值,例如“ User-Agent”和“ Accept-Language”等。
  5. We can call getResponseCode() to get the response HTTP code. This way we know if the request was processed successfully or there was any HTTP error message thrown.我们可以调用getResponseCode()来获取响应HTTP代码。 这样,我们就知道请求是否已成功处理,或者是否抛出任何HTTP错误消息。
  6. For GET, we can simply use Reader and InputStream to read the response and process it accordingly.对于GET,我们可以简单地使用Reader和InputStream读取响应并进行相应处理。
  7. For POST, before we read response we need to get the OutputStream from HttpURLConnection instance and write POST parameters into it.对于POST,在读取响应之前,我们需要从HttpURLConnection实例获取OutputStream并将POST参数写入其中。

HttpURLConnection示例 (HttpURLConnection Example)

Based on the above steps, below is the example program showing usage of HttpURLConnection to send Java GET and POST requests.

根据上述步骤,以下是示例程序,该程序显示HttpURLConnection用法来发送Java GET和POST请求。

HttpURLConnectionExample.java code:

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) { // successBufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));String inputLine;StringBuffer response = new StringBuffer();while ((inputLine = in.readLine()) != null) {response.append(inputLine);}in.close();// print resultSystem.out.println(response.toString());} else {System.out.println("GET request not worked");}}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 - STARTcon.setDoOutput(true);OutputStream os = con.getOutputStream();os.write(POST_PARAMS.getBytes());os.flush();os.close();// For POST only - ENDint responseCode = con.getResponseCode();System.out.println("POST Response Code :: " + responseCode);if (responseCode == HttpURLConnection.HTTP_OK) { //successBufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));String inputLine;StringBuffer response = new StringBuffer();while ((inputLine = in.readLine()) != null) {response.append(inputLine);}in.close();// print resultSystem.out.println(response.toString());} else {System.out.println("POST request not worked");}}}

When we execute the above program, we get below response.

当我们执行上面的程序时,我们得到下面的响应。

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

Just compare it with the browser HTTP response and you will see that it’s same. You can also save response into any HTML file and open it to compare the responses visually.

只需将其与浏览器的HTTP响应进行比较,您就会发现它是相同的。 您还可以将响应保存到任何HTML文件中,然后将其打开以直观地比较响应。

Quick Tip: If you have to send GET/POST requests over HTTPS protocol, then all you need is to use javax.net.ssl.HttpsURLConnection instead of java.net.HttpURLConnection. Rest all the steps will be same as above, HttpsURLConnection will take care of SSL handshake and encryption.

快速提示 :如果必须通过HTTPS协议发送GET / POST请求,则只需使用javax.net.ssl.HttpsURLConnection而不是java.net.HttpURLConnection 。 其余所有步骤与上面相同, HttpsURLConnection将负责SSL握手和加密。

翻译自: https://www.journaldev.com/7148/java-httpurlconnection-example-java-http-request-get-post

Java HttpURLConnection示例– Java HTTP请求GET,POST相关推荐

  1. 大数据 java 代码示例_Java变量类型与示例

    大数据 java 代码示例 Java变量 (Java variables) Variables are the user-defined names of the memory blocks, and ...

  2. Java RandomAccessFile示例

    Java RandomAccessFile provides the facility to read and write data to a file. RandomAccessFile works ...

  3. java 方法 示例_Java方法参考类型和示例

    java 方法 示例 Java Method Reference was introduced in Java 8, along with lambda expressions. The method ...

  4. Java try-catch示例

    Java try-catch block is used to handle exceptions in the program.Java try-catch块用于处理程序中的异常. The code ...

  5. java多线程示例_Java线程示例

    java多线程示例 Welcome to the Java Thread Example. Process and Thread are two basic units of execution. C ...

  6. Java FileWriter示例

    Java FileWriter (Java FileWriter) Java FileWriter class is a part of java.io package.Java FileWriter ...

  7. Java锁示例– ReentrantLock

    Welcome to Java Lock example tutorial. Usually when working with multi-threaded environment, we use ...

  8. java 泛型示例_Java泛型示例教程–泛型方法,类,接口

    java 泛型示例 Java Genrics is one of the most important features introduced in Java 5. Java Genrics是Java ...

  9. Java FileNameFilter示例

    Java FilenameFilter interface can be implemented to filter file names when File class listFiles() me ...

最新文章

  1. CPU 空闲时在干嘛?
  2. 四大组建进程间通信--基础
  3. TextScanner:旷视新作文字识别新突破,确保字符阅读顺序
  4. python从入门到精通需要多久--零基础学Python,从入门到精通需要多长时间
  5. python和c混编_python与C、C++混编的四种方式(小结)
  6. Java面试题:热情盛夏,分享Java大厂面试百题
  7. 磁盘阵列(RAID)
  8. 总结一下目标检测与跟踪
  9. mfc 子窗体 按钮不触发_PIE二次开发在子窗体中选择主窗体中的文件
  10. 【NLP 自然语言处理】自然语言处理技术难点和挑战
  11. 使用Android Studio和阿里云数据库实现一个远程聊天程序
  12. 2020年东北三省数学建模联赛赛题
  13. windows记事本自动换行
  14. python爬取网易云音乐 专辑图片+歌词
  15. 手工转换中缀式与前、后缀式(转)
  16. kubernet-- windows之kubectl的安装及使用(巧克力)
  17. 2021前端面试总结及反思
  18. 跨境追踪(ReID)多粒度网络(MGN)详解及代码实现(2)
  19. 基于stm32物联网开发板(2)--LCD屏幕
  20. Chrome版本与chromedriver兼容版本对照表

热门文章

  1. [转载] 不少Gate或Node运算子 的反向传播代码
  2. [转载] 终于来了!TensorFlow 2.0入门指南(上篇)
  3. [转载] 实训心得体会
  4. 排序类问题度量指标:Recall , MAP,MRR
  5. 初次使用uwsgi:no python application found, check your startup logs for errors
  6. 使用Yii 1.1框架搭建第一个web应用程序
  7. 通过JAVA操作SAE上的MY SQL数据库
  8. 使用NHibernate, Oracle Clob/NClob无法插入
  9. ural 1012K-based Numbers. Version 2 1013. K-based Numbers. Version 3
  10. javascript 判断string是否包含某个字符串