java HttpURLConnection实现简单的网络请求

目录

  • 演示
  • 源码分析

演示

看效果:
java HttpURLConnection实现简单的网络请求_第1张图片

完整代码:

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnectionTest {
    public static void main(String[] args) {
        try {
            // 根据地址创建URL对象(网络访问的url)
            URL url = new URL("https://publicobject.com/helloworld.txt");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(5000);
            urlConnection.setConnectTimeout(5000);
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                InputStream is = urlConnection.getInputStream();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                int len = 0;
                byte buffer[] = new byte[1024];
                // 按照缓冲区的大小,循环读取
                while ((len = is.read(buffer)) != -1) {
                    // 根据读取的长度写入到os对象中
                    os.write(buffer, 0, len);
                }
                is.close();
//                os.close(); //无需关闭
                urlConnection.disconnect();
                String result = new String(os.toByteArray());
                System.out.println(result);
            } else {
                System.out.println("------------------连接失败-----------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


源码分析

下面这两篇文章,已经说的很详细了:
HttpURLConnection 源码解读
HttpURLConnection 源码分析

你可能感兴趣的:(Handler,java,开发语言)