一、原生实现GET请求

public static String Get(String url) {
    HttpURLConnection conn = null;
    InputStream is = null;
    BufferedReader br = null;
    String line = null;
    StringBuilder sb = new StringBuilder();
    try {
        //获取URL连接对象强转为HTTPURL连接对象
        conn = (HttpURLConnection) new URL(url).openConnection();
        //设置HTTP请求方式为GET
        conn.setRequestMethod("GET");
        //设置连接超时时间为3秒
        conn.setConnectTimeout(3000);
        //设置读取时间超时为5秒
        conn.setReadTimeout(5000);
        // 设置请求头
        conn.setRequestProperty("Content-Type", "text/html;charset=utf-8");
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml,application/json;");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36");
        //发送请求
        conn.connect();
        //获取响应码,判断请求是否成功
        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((line = br.readLine()) != null) {
                // 当line不为null时,将line追加到sb中
                sb.append(line + "\n");
            }
        } else {
            // 返回错误信息
            return "ResponseCode is Error:" + conn.getResponseCode();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 释放IO流
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 返回sb的String内容
    return sb.toString();
}

问:怎么没有GET传参的方法?
答:一般我们会直接通过QueryString将多个键值的参数用&连接再与URL直接拼接,所以实际上我们还是只做了请求定向的链接,所以不需要传参的方法

二、原生实现POST请求

public static String Post(String url, String requestContent) {
    System.out.println("请求的URL:"+url);
    System.out.println("请求的参数:"+requestContent);
    HttpURLConnection conn = null;
    OutputStream os = null;
    BufferedWriter bw = null;
    InputStream is = null;
    String line = null;
    StringBuilder sb = new StringBuilder();
    BufferedReader br = null;
    try {
        // 获取URL连接对象强转为HTTPURL连接对象
        conn = (HttpURLConnection) new URL(url).openConnection();
        //设置请求头
        conn.setRequestProperty("Connection","keep-alive");
        conn.setRequestMethod("POST");
        //因为POST请求需要对流进行读写,所以需要设置输入输出均为true
        conn.setDoInput(true);
        conn.setDoOutput(true);
        // 设置超时时间
        conn.setConnectTimeout(3000);
        conn.setReadTimeout(15000);
        // 设置请求头
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml,application/json,application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36");
        // 将POST参数转为字节数组写到流中并刷新流(这一步相当于提交参数)
        conn.getOutputStream().write(requestContent.getBytes("UTF-8"));
        conn.getOutputStream().flush();
        // 获取响应码,判断请求是否成功
        if (conn.getResponseCode()==200){
            is = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while((line=br.readLine())!=null){
                sb.append(line+"\n");
            }
        }else{
            // 返回错误信息
            return "ResponseCode is Error:" + conn.getResponseCode();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        // 释放IO流
        if(br!=null){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(bw!=null){
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 返回sb的String内容
    return sb.toString();
}

问:为什么我的不成功?
答:请检查代码是否与我的完全一致,还有POST请求头中的Content-Type有几种固定的格式,并非你想写什么就可以写什么,就比如,如果我设置Content-Type为text/html;charset=utf-8,在GET请求下是正常的,在POST请求中是不行的,无法正确提交你的参数,因为你的参数并非是html格式的

三、POST请求中的常见Content-Type

1. 以QueryString的形式去提交POST参数

你需要使用的Content-Type为application/x-www-form-urlencoded

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

2. 以FormData的形式去提交POST参数

你需要使用的Content-Type为multipart/form-data

conn.setRequestProperty("Content-Type", "multipart/form-data");

3. 以Json格式去提交POST参数

你需要使用的Content-Type为application/json

conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

问:啥叫QueryString,FormData,Json?
答:请百度

原文作者:絷缘
作者邮箱:zhiyuanworkemail@163.com
原文地址:https://zhiyuandnc.github.io/JavaHttp/
版权声明:本文为博主原创文章,转载请注明原文链接作者信息