In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to use HttpURLConnection for you. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
The most commonly used Http request is that get and post,get requests can get static pages, or you can put parameters after the URL string. The difference passed to servlet,post and get is that the parameters of post are not placed in the URL string, but in the body of the http request.
In Java, you can use HttpURLConnection to initiate these two kinds of requests, and understanding this kind of request is very helpful for understanding soap and writing automated test code for servlet.
The following code briefly describes how to make both requests using HttpURLConnection and how to pass parameters:
Public class HttpInvoker {public static final String GET_URL = "http://localhost:8080/welcome1"; public static final String POST_URL = "http://localhost:8080/welcome1" Public static void readContentFromGet () throws IOException / / piece together the URL string of the get request, using URLEncoder.encode to encode special and invisible characters String getURL = GET_URL + "? username=" + URLEncoder.encode ("fat man", "utf-8"); URL getUrl = new URL (getURL) / / according to the patchwork of URL, open the connection, and the URL.openConnection function will return objects of different URLConnection subclasses according to the type of URL, where URL is a http, so what is actually returned is HttpURLConnection HttpURLConnection connection = (HttpURLConnection) getUrl .openConnection () / / to connect, but in fact get request will not actually send to / / server connection.connect () in the connection.getInputStream () function of the next sentence; / / get the input stream and use Reader to read BufferedReader reader = new BufferedReader (new InputStreamReader (connection.getInputStream (); System.out.println ("= =") System.out.println ("Contents of get request"); System.out.println ("= ="); String lines; while ((lines = reader.readLine ())! = null) {System.out.println (lines);} reader.close (); / / disconnect connection.disconnect () System.out.println ("= ="); System.out.println ("Contents of get request ends"); System.out.println ("=");} public static void readContentFromPost () throws IOException {/ / Post request url, unlike get, does not require the parameter URL postUrl = new URL (POST_URL) / / Open the connection HttpURLConnection connection = (HttpURLConnection) postUrl .openConnection (); / / Output to the connection. Default is / / false, set to true because post / / method must write something to the / / connection / / sets whether to output to connection, because this is a post request, and the parameter needs to be placed in the body of / / http, so it needs to be set to true connection.setDoOutput (true); / / Read from the connection. Default is true. Connection.setDoInput (true); / / Set the post method. Default is GET connection.setRequestMethod ("POST"); / / Post cannot use caches / / Post request cannot use cache connection.setUseCaches (false); / / This method takes effects to / / every instances of this class. / / URLConnection.setFollowRedirects is the static function that acts on all URLConnection objects. / / connection.setFollowRedirects (true); / / This methods only / / takes effacts to this / / instance. / / URLConnection.setInstanceFollowRedirects is a member function and only acts on the current function connection.setInstanceFollowRedirects (true); / / Set the content type to urlencoded, / / because we will write / / some URL-encoded content to the / / connection. Settings above must be set before connect! / / configure the Content-type of this connection, which is / / configured as application/x-www-form-urlencoded, which means that the body is the form parameter encoded by urlencoded Below we can see that we use URLEncoder.encode / / to encode connection.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded") for the body content. / / connection, the configuration from postUrl.openConnection () to here must be completed before connect. / / Note that connection.getOutputStream implicitly carries out connect. Connection.connect (); DataOutputStream out = new DataOutputStream (connection. GetOutputStream ()); / / The URL-encoded contend / / text, which is actually the same as in get's URL'?' The resulting parameter string is consistent with String content = "firstname=" + URLEncoder.encode ("a fat man", "utf-8"); / / DataOutputStream.writeBytes writes 16-bit unicode characters in the string to out.writeBytes (content); out.flush (); out.close () in the stream in 8-bit character form. / / flush and close BufferedReader reader = new BufferedReader (new InputStreamReader (connection.getInputStream (); String line; System.out.println ("="); System.out.println ("Contents of post request"); System.out.println ("=") While ((line = reader.readLine ())! = null) {System.out.println (line);} System.out.println ("="); System.out.println ("Contents of post request ends"); System.out.println ("= ="); reader.close (); connection.disconnect () } / * * / / * * @ param args * / public static void main (String [] args) {/ / TODO Auto-generated method stub try {readContentFromGet (); readContentFromPost ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace () }}}
The above readContentFromGet () function produces a get request, passing servlet a username parameter with a value of "fat man".
The readContentFromPost () function produces a post request, which is passed to servlet with a firstname parameter with the value "a fat man".
The HttpURLConnection.connect function actually establishes a tcp connection to the server and does not actually send an http request. Either the post or the get,http request is actually not officially sent until the function HttpURLConnection.getInputStream ().
In readContentFromPost (), order is the top priority, and all configuration of the connection object (that stack of set functions) must be done before the connect () function is executed. On the other hand, the write operation to outputStream must be before the read operation of inputStream. These orders are actually determined by the format of the http request.
The http request actually consists of two parts, one is the http header, and all the configurations for this http request are defined in the http header, and the other is the body content. In the connect () function, the http header is generated according to the configuration value of the HttpURLConnection object, so all configurations must be ready before calling the connect function.
Immediately after the http header is the body of the http request, and the body is written through outputStream. In fact, outputStream is not a network stream, but at best a string stream. What is written into it is not immediately sent to the network, but after the stream is closed, the http body is generated according to the input.
At this point, what http requests is ready. When the getInputStream () function is called, the prepared http request is formally sent to the server and an input stream is returned to read the server's return information for the http request. Since the http request has already been sent (including the http header and body) during getInputStream, it is meaningless to set the connection object (modify the information of the http header) or write outputStream (modify the body) after the getInputStream () function, and performing these operations will lead to an exception.
As mentioned in the previous section, the OutputStream requested by post is not actually a network stream, but written to memory. In getInputStream, the content in the write stream is really merged as the body with the http request header generated according to the previous configuration into a real http request, and only at this time can it be really sent to the server.
The HttpURLConnection.setChunkedStreamingMode function can change this mode. When ChunkedStreamingMode is set, instead of waiting for OutputStream to be turned off to generate a complete one-off http request, the http request header is sent first, and the body content is transmitted to the server in real time in the form of a network stream. Instead of telling the server the length of the http body, this mode is suitable for sending large or inaccessible length data, such as files, to the server.
This is the end of the article on "how to use HttpURLConnection". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.