📜  Java的.net.URLConnection类在Java中(1)

📅  最后修改于: 2023-12-03 15:16:36.700000             🧑  作者: Mango

Java的.net.URLConnection类在Java中

一. 简介

Java的.net.URLConnection类提供了一种与URL之间交互的机制。它可以用来读取Web页面,以及与Web服务器进行交互等。

二. 使用URLConnection类

1. 创建URLConnection对象

以下是创建URLConnection对象的代码实例:

URL url = new URL("http://www.example.com/example.html");
URLConnection conn = url.openConnection();
2. 设定请求头

使用URLConnection类可以设置请求头,如下所示:

conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

设置请求头的作用是告诉服务器应该如何处理请求。在这个例子,设置User-Agent头,告诉服务器使用Mozilla Firefox浏览器打开请求页面。Accept-Language头是告诉服务器仅使用英语传输内容。

3. 发送数据

使用URLConnection类可以发送数据到Web服务器,如下所示:

conn.setDoOutput(true);

OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write("参数1=数据1&参数2=数据2");
out.flush();
out.close();

调用setDoOutput(true)方法后,才可以发送请求体(Message Body)。在这个例子中,发送的请求体是"参数1=数据1&参数2=数据2"。

4. 获取响应

使用URLConnection类可以获取Web服务器的响应,如下所示:

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

String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}

in.close();

使用getInputStream()方法可以获取Web服务器的响应。在这个例子中,读取Web服务器响应内容时,先将字节流转换为字符流。

5. 完整代码

以下是使用URLConnection类的完整代码实例:

import java.net.*;
import java.io.*;

public class URLConnectionExample {
    public static void main(String[] args) throws Exception {

        URL url = new URL("http://www.example.com/example.html");
        URLConnection conn = url.openConnection();

        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        conn.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write("参数1=数据1&参数2=数据2");
        out.flush();
        out.close();

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

        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        in.close();

        System.out.println(response.toString());

    }
}

三. 结论

Java的.net.URLConnection类提供了一种与URL之间交互的机制。它可以用来读取Web页面,以及与Web服务器进行交互等。可以使用URLConnection类创建连接、设定请求头、发送数据、读取响应等操作。