java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java原生post请求方式

Java中的原生post请求方式

作者:沙皮狗你不懂

这篇文章主要介绍了Java中的原生post请求方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

1.post请求方式(有参数)

因为请求地址为https 需要配置不验证证书

/**
     * post请求方式(有参数) 因为请求地址为https 需要配置不验证证书
     */
    public static String post(String strUrl, Map<String, Object> params) {
        try {
            // 添加信任主机
            trustAllHosts();
            // 创建连接
            URL url = new URL(strUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            // 不验证配置
            connection.setHostnameVerifier(DO_NOT_VERIFY);
            // 设置请求方式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("accept","*/*");
            connection.setRequestProperty("connection","Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置发送数据的格式json
            connection.setRequestProperty("Content-Type","application/json");
            // 设置token appkey
            connection.setRequestProperty("apikey","Z31jdnojkYFg3z3mXourHjP5gmpg9Ms9");
            // 设置接收数据的格式json
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            // 阿里巴巴的fastjson
            out.append(JSON.toJSONString(params));
            out.flush();
            out.close();
            // 请求成功
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                // 读取响应
                StringBuffer respResult = new StringBuffer();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    respResult.append(line);
                }
                reader.close();
                log.info("Req Success{}" + respResult.toString());
                return respResult.toString();
            }
        } catch (Exception e) {
            log.info("Req Error{}" + e.getMessage());
            return e.getMessage();
        }
        // 请求失败
        return null;
    }
/**
     * 不验证配置
     */
    private final static HostnameVerifier DO_NOT_VERIFY = (hostname, session) -> true;
    /**
     * 添加信任主机
     */
    private static void trustAllHosts() {
        // 创建不验证证书链的信任管理器 这里使用的是x509证书 此处的MyX509TrustManager()为实现重写方法
        TrustManager[] trustAllCerts = new TrustManager[]{new MyX509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {}
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {}
        }};
        // 安装所有信任的信任管理器
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            //HttpsURLConnection通过SSLSocket来建立与HTTPS的安全连接,SSLSocket对象是由SSLSocketFactory生成的。
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.post请求方式(无参数)

/**
     * post请求方式(无参数)
     */
    public static String post(String strUrl) {
        try {
            // 创建连接
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "keep-alive");
            // 设置接收数据的格式json
            connection.setRequestProperty("Accept", "application/json");
            // connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式json
            connection.connect();
            // 获取响应码
            int code = connection.getResponseCode();
            // 请求成功
            if (code == 200) {
                // 读取响应
                StringBuffer respResult = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    respResult.append(line);
                }
                reader.close();
                log.info("Req Success{}" + respResult.toString());
                return respResult.toString();
            }
        } catch (Exception e) {
            log.info("Req Error{}" + e.getMessage());
            return e.getMessage();
        }
        // 请求失败
        return null;
    }
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
 * 重写的X509TrustManager类
 */
public class MyX509TrustManager implements X509TrustManager { 
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) {}
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) {}
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null; 
    } 
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文