栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

Java--URLConnection--使用/实例

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java--URLConnection--使用/实例

原文网址:Java--URLConnection--使用/实例_IT利刃出鞘的博客-CSDN博客

简介

说明

        本文用示例介绍Java的网络类:URLConnection

作用

URL的openConnection() 返回一个 java.net.URLConnection。

  • 如果你连接HTTP协议的URL, openConnection() 方法返回 HttpURLConnection 对象。
  • 如果你连接的URL为一个 JAR 文件, openConnection() 方法将返回 JarURLConnection 对象。
  • 等等...
方法

方法

描述

Object getContent()

检索URL链接内容

Object getContent(Class[] classes)

检索URL链接内容

String getContentEncoding()

返回头部content-encoding字段值。

int getContentLength()

返回头部content-length字段值

String getContentType()

返回头部content-type字段值

int getLastModified()

返回头部last-modified字段值。

long getExpiration()

返回头部expires字段值。

long getIfModifiedSince()

返回对象的ifModifiedSince字段值。

public void setDoInput(boolean input)

URL连接可用于输入和/或输出。如果打算使用URL连接进行输入,则将DoInput标志设置为true

public void setDoOutput(boolean output)

URL连接可用于输入和/或输出。如果打算使用URL连接进行输出,则将DoOutput标志设置为tue

public InputStream getInputStream()throws IOException

返回URL的输入流,用于读取资源

public OutputStream getOutputStream()throws IOException

返回URL的输出流,用于写入资源。

public URL getURL()

返回URLConnection对象连接的URL

示例
package com.example.a;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class Demo {
    public static void main(String[] args) {
        URL url = null;

        try {
            url = new URL("https://knife.blog.csdn.net/article/details/124509399?name=Tony&age=25#abc");
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection connection = null;
            if (urlConnection instanceof HttpURLConnection) {
                connection = (HttpURLConnection) urlConnection;
            } else {
                System.out.println("请输入 URL 地址");
                return;
            }
            
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String urlString = "";
            String current;
            while ((current = in.readLine()) != null) {
                urlString += current;
            }
            
            System.out.println(urlString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

执行结果

会打印出相应url的html内容

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/984225.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号