原生URLConnection

GET请求与POST请求

在介绍HttpURLConnection前,我们还是再来说一下URL请求最常用的两种方式:GET请求与POST请求。

GET请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),以?分割URL和传输数据,参数之间以&相连,如:http://localhost:8080/test.do?name=test&password=123456。

GET请求发送的参数如果数据是英文字母或数字,则按原样发送,如果是空格,则转换为+,如果是中文或其他字符,则直接把字符串用BASE64加密,得出如 %E4%BD%A0%E5%A5%BD 这类似的字符串,其中%XX中的XX为该符号以16进制表示的ASCII。

POST请求的参数不是放在URL字符串里面,而是放在HTTP请求的正文内,请求的参数被封装起来以流的形式发送给服务端。

对于GET方式提交数据的大小,HTTP协议并没有硬性限制,但某些浏览器及服务器会对它进行限制,如IE对URL长度的限制是2083字节(2K+35)。理论上POST也没有限制,可传较大量的数据。

POST的安全性要比GET的安全性高。比如:通过GET提交数据,用户名和密码将明文出现在URL上,因为登录页面有可能被浏览器缓存,如果其他人查看浏览器的历史纪录,那么别人就可以拿到你的账号和密码了,除此之外,使用GET提交数据还可能会造成Cross-site request forgery(CSRF,跨站请求伪造)攻击。

HttpURLConnection简介

在JDK的java.net包中已经提供了访问HTTP协议的基本功能的类:HttpURLConnection。

HttpURLConnection是Java的标准类,它继承自URLConnection,可用于向指定网站发送GET请求、POST请求。它在URLConnection的基础上提供了如下便捷的方法:

int getResponseCode(); // 获取服务器的响应代码。
String getResponseMessage(); // 获取服务器的响应消息。
String getResponseMethod(); // 获取发送请求的方法。
void setRequestMethod(String method); // 设置发送请求的方法。

HttpURLConnection使用样例

package dev.lpf.http.utils;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * 使用 Http 的 UrlConnection
 */
@Slf4j
public class HttpUrlConnectionUtil {

    /**
     * 发送GET请求
     *
     * @param url
     * @param headers
     * @return
     */
    public static String sendGetRequest(String url, Map headers) {
        InputStream is = null;
        BufferedWriter writer = null;
        OutputStream output = null;
        HttpURLConnection conn = null;
        try {
            URL newUrl = new URL(url);
            conn = (HttpURLConnection) newUrl.openConnection();
            log.info("url:{}", conn.getURL());
            // 设置连接主机服务器的超时时间:15秒
            conn.setConnectTimeout(15 * 1000);
            // 设置读取远程返回的数据超时时间为10秒
            conn.setReadTimeout(10 * 1000);
            // 设置请求方式GET
            conn.setRequestMethod("GET");
            // Post请求不能使用缓存
            conn.setUseCaches(false);
            // 接受输入流
            conn.setDoInput(false);
            // 启动输出流,当需要传递参数时需要开启
            conn.setDoOutput(true);
            // 添加Header
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            HttpURLConnection finalConn = conn;
            if (headers != null) {
                headers.forEach((k, v) -> {
                    finalConn.setRequestProperty(k.toString(), v.toString());
                });
            }

            // 发起请求
            conn.connect();

            // 添加请求参数,注意:如果是GET请求,参数要写在URL中
            output = conn.getOutputStream();
            writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
            // 写入参数 用&分割
            // writer.write("demo=1");
            writer.flush();

            // 状态码
            int code = conn.getResponseCode();
            log.info("http code:{}", code);
            if (code == 200) {
                is = conn.getInputStream();
                String result = readInputStreamByReader(is);
                return result;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            conn.disconnect();
        }
        return null;
    }

    /**
     * 发送Post请求
     *
     * @param url
     * @param headers
     * @param body
     * @return
     */
    public static String sendPostRequest(String url, Map headers, Object body) {
        InputStream is = null;
        BufferedWriter writer = null;
        OutputStream output = null;
        HttpURLConnection conn = null;
        try {
            URL newUrl = new URL(url);
            conn = (HttpURLConnection) newUrl.openConnection();
            log.info("url:{}", conn.getURL());
            // 设置读去超时时间为10秒
            conn.setReadTimeout(10 * 1000);
            // 设置连接超时为10秒
            conn.setConnectTimeout(15 * 1000);
            // 设置请求方式,GET,POST
            conn.setRequestMethod("POST");
            // Post请求不能使用缓存
            conn.setUseCaches(false);
            // 接受输入流
            conn.setDoInput(true);
            // 启动输出流,当需要传递参数时需要开启
            conn.setDoOutput(true);
            // 添加Header
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            HttpURLConnection finalConn = conn;
            if (headers != null) {
                headers.forEach((k, v) -> {
                    finalConn.setRequestProperty(k.toString(), v.toString());
                });
            }

            // 添加Body
            String bodyJson = JSON.toJSONString(body);
            log.info("req body:{}", bodyJson);

            // 发起请求
            conn.connect();
            output = conn.getOutputStream();
            // 写入参数
            writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
            writer.write(bodyJson);

            // 状态码
            int code = conn.getResponseCode();
            log.info("http code:{}", code);
            if (code == 200) {
                is = conn.getInputStream();
                String result = readInputStreamByReader(is);
                return result;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            conn.disconnect();
        }
        return null;
    }

    /**
     * 把输入流的内容转化成字符串
     *
     * @param is
     * @return
     */
    public static String readInputStreamByReader(InputStream is) {
        StringBuffer sbf = new StringBuffer();
        // 获取服务端响应,通过输入流来读取URL的响应
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                sbf.append(line);
                sbf.append("\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("IOException:{}", e.getMessage());
        }
        return sbf.toString();
    }
}

HttpsURLConnection使用样例


package dev.lpf.http.utils;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import lombok.extern.slf4j.Slf4j;

/**
 * 使用 Https 的 UrlConnection
 */
@Slf4j
public class HttpsUrlConnectionUtil {

    /**
     * 发送GET请求
     *
     * @param url
     * @param headers
     * @return
     */
    public static String sendGetRequest(String url, Map headers) {
        HttpsURLConnection conn = null;
        InputStream is = null;
        OutputStream output = null;
        BufferedReader reader = null;
        BufferedWriter writer = null;

        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }};
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tm, new SecureRandom());

            conn = (HttpsURLConnection) new URL(url).openConnection();
            log.info("url:{}", conn.getURL());
            // 设置请求方式GET
            conn.setRequestMethod("GET");
            // 设置读去超时时间为10秒
            conn.setReadTimeout(10 * 1000);
            // 设置连接超时为10秒
            conn.setConnectTimeout(15 * 1000);
            // Post请求不能使用缓存
            conn.setUseCaches(false);
            // 接受输入流
            conn.setDoInput(true);
            // 启动输出流,当需要传递参数时需要开启
            conn.setDoOutput(true);
            // 添加Header
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            HttpsURLConnection finalConn = conn;
            if (headers != null) {
                headers.forEach((k, v) -> {
                    finalConn.setRequestProperty(k.toString(), v.toString());
                });
            }

            // 发起请求
            conn.connect();
            output = conn.getOutputStream();
            // 写入参数 用&分割
            // writer.write("demo=1");
            writer.flush();

            // 状态码
            int code = conn.getResponseCode();
            log.info("http code:{}", code);
            if (code == 200) {
                is = conn.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line;
                StringBuffer sbf = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    sbf.append(line);
                    sbf.append("\r\n");
                }
                return sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            conn.disconnect();
        }
        return null;
    }

    /**
     * 发送Post请求
     * 
     * @param url
     * @param headers
     * @param body
     * @return
     */
    public static String sendPostRequest(String url, Map headers, Object body) {
        HttpsURLConnection conn = null;
        InputStream is = null;
        OutputStream output = null;
        BufferedReader reader = null;
        BufferedWriter writer = null;

        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }};
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tm, new SecureRandom());

            conn = (HttpsURLConnection) new URL(url).openConnection();
            log.info("url:{}", conn.getURL());
            // 设置请求方式,GET,POST
            conn.setRequestMethod("POST");
            // 设置读去超时时间为10秒
            conn.setReadTimeout(10 * 1000);
            // 设置连接超时为10秒
            conn.setConnectTimeout(15 * 1000);
            // Post请求不能使用缓存
            conn.setUseCaches(false);
            // 接受输入流
            conn.setDoInput(true);
            // 启动输出流,当需要传递参数时需要开启
            conn.setDoOutput(true);
            // 添加Header
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            HttpsURLConnection finalConn = conn;
            if (headers != null) {
                headers.forEach((k, v) -> {
                    finalConn.setRequestProperty(k.toString(), v.toString());
                });
            }

            // 添加Body
            String bodyJson = JSON.toJSONString(body);
            log.info("req body:{}", bodyJson);

            // 发起请求
            conn.connect();
            output = conn.getOutputStream();
            // 写入参数
            writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
            writer.write(bodyJson);

            // 状态码
            int code = conn.getResponseCode();
            log.info("http code:{}", code);
            if (code == 200) {
                is = conn.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line;
                StringBuffer sbf = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    sbf.append(line);
                    sbf.append("\r\n");
                }
                return sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            conn.disconnect();
        }
        return null;
    }
}

results matching ""

    No results matching ""