Example of using URL + urlconnection in Java network programming
catalogue
HTTP get and post
From URLs to local files
In Java Net package contains two interesting classes: URL class and urlconnection class. These two classes can be used to create a connection between a client and a web server (HTTP server). Here is a simple code example:
HTTP get and post
By default, urlconnection sends an HTTP get request to the web server. If you want to send an HTTP post request, call urlconnection Setdooutput (true) method, as follows:
Once you call setdooutput (true), you can open the OutputStream of urlconnection as follows:
You can use this OutputStream to write any data to the corresponding HTTP request, but you should remember to convert it into URL encoding (for the explanation of URL encoding, please Google).
When you finish writing data, remember to close OutputStream.
From URLs to local files
URLs are also called uniform resource locators. If your code doesn't care whether the file comes from the network or the local file system, the URL class is another way to open the file.
The following is an example of how to open a local file system file using the URL class:
Note: the only difference between this and accessing a file on a web server via HTTP is the URL: "file: / C: / data / test txt”。
summary
The above is all about the example of URL + urlconnection in Java network programming. I hope it will be helpful to you. Welcome to: detailed explanation and code examples of static internal classes in Java, object classes for Java source code analysis, etc. if there are deficiencies, please leave a message to point out. Thank you for your support!