java代码访问百度,返回html页面代码

package Mytest.model.test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpBaiduDemo {
    public static void main(String[] args) throws IOException {
        /**
         * java代码访问百度
         * 1.创建URL对象
         * 2.创建Http链接
         */
        URL url = new URL("http://www.baidu.com");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        /**
         * 3.设置请求方式
         * 4.设施请求内容类型
         */
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        /**
         * 5.设置请求参数
         * 6.使用输出流发送参数
         */
        //String content="username:";
        //OutputStream outputStream = httpURLConnection.getOutputStream();
        //outputStream.write(content.getBytes());
        /**
         * 7.使用输入流接受数据
         */
        InputStream inputStream = httpURLConnection.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//此处可以用Stringbuffer等接收
        byte[] b = new byte[1024];
        int len=0;
        while (true) {
            len=inputStream.read(b);
            if (len == -1) {
                break;
            }
            byteArrayOutputStream.write(b,0,len);
        }
        System.out.println(byteArrayOutputStream.toString());
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文子阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值