java 原生http请求

java原生http请求的实现是依赖 java.net.URLConnection

post请求的demo

public class Main {

    public static void main(String[] args) {
        postDemo();
    }

    /**
     * POST请求
     */
    public static void postDemo() {
        try {
            // 请求的地址
            String spec = "http://localhost:9090/formTest";
            // 根据地址创建URL对象
            URL url = new URL(spec);
            // 根据URL对象打开链接
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();
            // 设置请求方法
            urlConnection.setRequestMethod("POST");
            // 设置请求的超时时间
            urlConnection.setReadTimeout(5000);
            urlConnection.setConnectTimeout(5000);
            // 传递的数据
            String data = "name=" + URLEncoder.encode("aaa", "UTF-8")
                    + "&school=" + URLEncoder.encode("bbbb", "UTF-8");
            // 设置请求的头
            urlConnection.setRequestProperty("Connection", "keep-alive");
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length));
            // 发送POST请求必须设置允许输出
            urlConnection.setDoOutput(true);
            // 发送POST请求必须设置允许输入
            urlConnection.setDoInput(true);
            //setDoInput的默认值就是true
            //获取输出流,将参数写入
            OutputStream os = urlConnection.getOutputStream();
            os.write(data.getBytes());
            os.flush();
            os.close();
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                // 获取响应的输入流对象
                InputStream is = urlConnection.getInputStream();
                // 创建字节输出流对象
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                // 定义读取的长度
                int len = 0;
                // 定义缓冲区
                byte[] buffer = new byte[1024];
                // 按照缓冲区的大小,循环读取
                while ((len = is.read(buffer)) != -1) {
                    // 根据读取的长度写入到os对象中
                    byteArrayOutputStream.write(buffer, 0, len);
                }
                // 释放资源
                is.close();
                byteArrayOutputStream.close();
                // 返回字符串
                String result = new String(byteArrayOutputStream.toByteArray());
                System.out.println(result);

            } else {
                System.out.println("请求失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  

posted on 2020-09-17 22:24  幽人月  阅读(2129)  评论(0编辑  收藏  举报