根据对方提供的url获取对方返回的字符串信息

本文介绍了一个用于解析URL并获取返回字符串信息的方法。该方法通过建立URL连接,设置输入输出方式,并利用BufferedReader读取响应内容,最终将读取到的信息拼接成完整的字符串返回。

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

/*
	 * 解析URL获取返回的字符串信息
	 */
	private  String doHttpRequest(String url) {
        StringBuffer result = new StringBuffer();
        BufferedReader in = null;
        try {
        	URLConnection connection = null;
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            connection = realUrl.openConnection();
        	// 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter out = new PrintWriter(connection.getOutputStream());         
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"GBK"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
                // flush输出流的缓冲
                out.flush();
            }
        } catch (Exception e) {
        }finally {// 使用finally块来关闭输入流
            try { 
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result.toString();
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值