Home >Java >javaTutorial >How to use URLConnection function in Java for network operations

How to use URLConnection function in Java for network operations

王林
王林Original
2023-06-26 18:10:531238browse

As a cross-platform programming language, Java is often used to develop network applications. Whether you are developing web crawlers or performing network communications, Java provides many network-related class libraries. Among them, the most basic one in network operations is the URLConnection class. This article will introduce how to use the URLConnection class for network operations.

1. Overview of URLConnection class

URLConnection is the base class in Java used to access resources connected to URLs. It provides an extensible mechanism for accessing resources. You can set request parameters, establish connections, write data, and read responses through the setRequestProperty method. URLConnection can handle multiple types of URL resources: HTTP, HTTPS, FTP, etc.

2. URL construction

URLConnection is built in Java, and you need to first construct a URL object to access network resources. You can use the URL class under the java.net package to construct a URL object. The constructor of the URL class is as follows:

public URL(String spec) throws MalformedURLException;

Among them, spec is a URL address in the form of a string. For example:

URL url = new URL("http://www.example.com/file.txt");

3. URLConnection connection and configuration

1. Establish a connection

URL.openConnection() method will return a URLConnection object connected to the resource. For example:

URLConnection conn = url.openConnection();

2. Set request parameters

URLConnection provides some APIs for setting HTTP request parameters, for example:

conn.setRequestMethod("GET");//Set the request method

The available request methods are GET, POST, HEAD, PUT, DELETE, TRACE, OPTIONS and CONNECT.

conn.setDoOutput(true);//Whether output is allowed

conn.setDoInput(true);//Whether input is allowed

conn.setRequestProperty("User-Agent ", "Mozilla/5.0 (Windows NT 10.0; Win64; Executed before the conn.connect() method.

3. Establish a connection and write data

The URLConnection.connect() method will try to connect to the resource, but it will not send the request immediately, and it cannot know whether the server supports the requested method. You must call the setDoOutput(true) method to set the allowed output data before calling the getOutputStream() method to obtain the output stream. For example:

conn.setDoOutput(true);

OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());

out.write("name=value");//Writing required Sent data
out.flush();
out.close();
##4. Read the response

When getting the response from the server, you can call the getInputStream() method Get the server's response content and convert it into data that the program can read. For example:

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String line;

while ((line = in.readLine()) != null) {

System.out.println(line);

}
in.close();

4. Complete example

The following is a complete example to read remote XML data. And parse the content:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.URL;

import java.net.URLConnection;

public class URLConnectionExample {

public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.example.com/sample.xml");
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, xml = "";
    while ((line = in.readLine()) != null) {
        xml += line;
    }
    in.close();
    System.out.println("XML content: "+xml);
}

}

The above is how to use the URLConnection class to perform network operations. You can set request parameters through the setRequestProperty method and read the response content through the getInputStream method. Use the URLConnection class to implement basic network operations, such as reading HTML, XML and other web content. At the same time, for some more complex network operations, other network libraries can also be used for development.

The above is the detailed content of How to use URLConnection function in Java for network operations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn