java-URLConnection网络数据收取

本文介绍了一个使用Java的URLConnection类从指定URL获取数据的示例代码。该代码展示了如何设置连接超时、读取超时、禁用缓存,并设置User-Agent头部信息。通过InputStreamReader和BufferedReader读取响应内容,最终将读取到的数据输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过url创建connection方式收取

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

@SuppressWarnings("all")
public class Test {
    public static void main(String[] args)throws Exception {
        URL url = new  URL("http://192.168.0.215:8080/tsportal/web/system/userOnlineCount");
        URLConnection connection =  url.openConnection();
        connection.setConnectTimeout(20000);
        connection.setReadTimeout(20000);
        connection.setUseCaches(false);
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11");
        InputStream is = connection.getInputStream(); 
        InputStreamReader inputStreamReader = new InputStreamReader(is, "utf-8");
        BufferedReader bis = new BufferedReader(inputStreamReader); 
        String line = null; 
        StringBuffer result = new StringBuffer(); 
        while ((line = bis.readLine()) != null) { 
            result.append(line); 
        } 
        System.out.println(result.toString()); 
    }

}

 

转载于:https://www.cnblogs.com/hwaggLee/p/4873567.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值