700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java HttpURLConnection示例– Java HTTP请求GET POST

Java HttpURLConnection示例– Java HTTP请求GET POST

时间:2019-02-14 00:10:58

相关推荐

Java HttpURLConnection示例– Java HTTP请求GET POST

HttpURLConnectionclass frompackage can be used to send Java HTTP Request programmatically. Today we will learn how to useHttpURLConnectionin java program to sendGETandPOSTrequests and then print the response.

包中的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 nameduserNamewith value asPankajthen 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" "/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 behttps://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 nameuserNameand 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 usingHttpURLConnectionclass.

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

CreateURLobject from the GET/POST URL String.从GET / POST URL字符串创建URL对象。 Call openConnection() method on URL object that returns instance ofHttpURLConnection在返回HttpURLConnection实例的URL对象上调用openConnection()方法 Set the request method inHttpURLConnectioninstance, default value is GET.在HttpURLConnection实例中设置请求方法,默认值为GET。 Call setRequestProperty() method onHttpURLConnectioninstance to set request header values, such as “User-Agent” and “Accept-Language” etc.在HttpURLConnection实例上调用setRequestProperty()方法以设置请求标头值,例如“ User-Agent”和“ Accept-Language”等。 We can callgetResponseCode()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错误消息。 For GET, we can simply use Reader and InputStream to read the response and process it accordingly.对于GET,我们可以简单地使用Reader和InputStream读取响应并进行相应处理。 For POST, before we read response we need to get the OutputStream fromHttpURLConnectioninstance 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 ofHttpURLConnectionto 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 .HttpURLConnection;import .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, 9:31:04 PM IST. </P></body></html>GET DONEPOST Response Code :: 200<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/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.ssl.HttpsURLConnectioninstead of.HttpURLConnection. Rest all the steps will be same as above,HttpsURLConnectionwill take care of SSL handshake and encryption.

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

翻译自: /7148/java-httpurlconnection-example-java-http-request-get-post

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。