21xrx.com
2024-09-20 05:35:02 Friday
登录
文章检索 我的文章 写文章
Java程序如何访问Internet上的对象
2023-06-16 11:36:19 深夜i     --     --
Java URLConnection 访问Internet

在Java程序中,我们经常需要访问Internet上的对象,比如网页、图片等资源。Java提供了多种方式来实现这一功能,其中最常见的方法是使用Java内置的URLConnection类。

使用URLConnection访问网页

以下是一个示例程序,演示如何使用URLConnection类来访问网页并读取其内容:


import java.net.*;

import java.io.*;

public class URLConnectionExample {

  public static void main(String[] args) {

   try {

     URL url = new URL("https://www.baidu.com");

     URLConnection conn = url.openConnection();

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

     String line;

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

      System.out.println(line);

     }

     reader.close();

   } catch (Exception e) {

     e.printStackTrace();

   }

  }

}

以上程序使用URL类创建一个URL对象,并使用openConnection方法获取URLConnection对象。然后使用BufferedReader来逐行读取URLConnection的输入流,并输出到控制台。

使用URLConnection下载文件

现在,我们来看一下如何使用URLConnection来下载文件:


import java.net.*;

import java.io.*;

public class URLConnectionDownloadExample {

  public static void main(String[] args) {

   try {

     URL url = new URL("https://www.example.com/image.jpg");

     URLConnection conn = url.openConnection();

     InputStream in = conn.getInputStream();

     FileOutputStream out = new FileOutputStream("image.jpg");

     byte[] buffer = new byte[1024];

     int len;

     while ((len = in.read(buffer)) != -1) {

      out.write(buffer, 0, len);

     }

     out.close();

     in.close();

   } catch (Exception e) {

     e.printStackTrace();

   }

  }

}

以上程序使用URL类创建一个URL对象,并使用openConnection方法获取URLConnection对象。然后使用InputStream来读取URLConnection的输入流,并将其写入文件。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章