返回博主主页

java网络请求HttpURLConnection

1.

@Test(timeout = 1000)
    public void testNet() throws IOException {
        URL url = new URL("https://cn.bing.com/search?q=fd");
        URLConnection connection = url.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

        httpURLConnection.setRequestMethod("GET");  //设置一些属性


        InputStream inputStream = httpURLConnection.getInputStream();//这个过程可能会阻塞,得到服务器响应的数据
        
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);//对输入流进行包装
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String line;
        while((line=reader.readLine())!=null){
            System.out.println(line);
        }
        
        //关闭输入流对象
        while (reader!=null){
            reader.close();
            reader=null;
        }
        while(inputStreamReader!=null){
            inputStreamReader.close();
            inputStreamReader=null;
        }
        while(inputStream!=null){
            inputStream.close();
            inputStream=null;
        }
    }

 

posted @ 2021-11-03 15:15  懒惰的星期六  阅读(535)  评论(0编辑  收藏  举报

Welcome to here

主页