HTTPS-post请求

参考代码:http://www.programcreek.com/java-api-examples/javax.net.ssl.HttpsURLConnection

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ndkey.sms.sender.submail;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ndkey.config.ConfigType;
import com.ndkey.exception.DkRuntimeException;
import com.ndkey.sms.SmsException;
import com.ndkey.sms.sender.SmsSender;
import com.ndkey.sms.sender.config.URLConfig;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author zxf
 */
public class SubmailSmsSender implements SmsSender {

    private final Logger _logger = LoggerFactory.getLogger(this.getClass());
    private final static ObjectMapper _objectMapper = new ObjectMapper();
    private static final List<ConfigType> CONFIG_TYPES = new LinkedList<ConfigType>();
    private Map<String, String> configs = new HashMap<String, String>();
    private CloseableHttpClient httpClient = null;

    static {
        CONFIG_TYPES.add(new URLConfig());
        CONFIG_TYPES.add(new AppIdConfig());
        CONFIG_TYPES.add(new ProjectConfig());
        CONFIG_TYPES.add(new SignatureConfig());
        CONFIG_TYPES.add(new VarsConfig());
    }

    @Override
    public String getName() {
        return "SUBMAIL 短信通道";
    }

    @Override
    public void init() throws SmsException {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (Exception ex) {
            _logger.error("sms init failed. " + ex.getMessage(), ex);
            throw new SmsException("sms init failed. " + ex.getMessage(), ex);
        }
    }

    @Override
    public void destroy() {
        try {
            httpClient.close();
        } catch (IOException ex) {
            _logger.error("关闭httpClient失败", ex);
        }
    }

    @Override
    public List<ConfigType> getConfigTypes() {
        return CONFIG_TYPES;
    }

    @Override
    public Map<String, String> getConfigs() {
        return configs;
    }

    @Override
    public void setConfigs(Map<String, String> configs) {
        this.configs = configs;
        for (ConfigType type : getConfigTypes()) {
            if (!this.configs.containsKey(type.getUuid())) {
                this.configs.put(type.getUuid(), type.getDefaultValue());
            }
        }
    }

    public String getUrl() {
        return configs.get(URLConfig.UUID);
    }

    public String getAppId() {
        return configs.get(AppIdConfig.UUID);
    }

    public String getProject() {
        return configs.get(ProjectConfig.UUID);
    }

    public String getSignature() {
        return configs.get(SignatureConfig.UUID);
    }
    
    public String getVars(String message){
        return configs.get(VarsConfig.UUID).replace("{msg}", message);
    }

    @Override
    public void sendMessage(String mobile, String message) throws SmsException {
        CloseableHttpResponse response = null;
        try {
            Map<String, String> infoMap = new HashMap<String, String>();
            infoMap.put("appid", getAppId());
            infoMap.put("to", mobile);
            infoMap.put("project", getProject());
            infoMap.put("signature", getSignature());
            infoMap.put("vars", URLEncoder.encode(getVars(message), "UTF-8"));
            message = _objectMapper.writeValueAsString(infoMap);
            HttpPost httpPost = new HttpPost(getUrl());
            _logger.debug(message);
            httpPost.setEntity(new StringEntity(message, ContentType.create("application/json")));
            response = httpClient.execute(httpPost);
            for (String line : IOUtils.readLines(response.getEntity().getContent())) {
                _logger.debug(line);
            }
        } catch (IOException ex) {
            _logger.error("Failed to send message.", ex.getMessage());
            throw new DkRuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(response);
        }
    }

    private final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }

        public void checkClientTrusted(X509Certificate[] chain,
                String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain,
                String authType) throws CertificateException {
        }
    }};

}

=======================================================================

这个方式部分已被deprecate了!

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ndkey.auditproxy.yuexing;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ndkey.auditproxy.AuditProxy;
import com.ndkey.auditproxy.AuditProxyException;
import com.ndkey.auditproxy.LoginRequest;
import com.ndkey.auditproxy.LogoutRequest;
import com.ndkey.auditproxy.config.TimeoutConfig;
import com.ndkey.config.ConfigType;
import com.ndkey.exception.DkRuntimeException;
import com.ndkey.net.MacAddress;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author zxf
 */
public class YuexingProxy implements AuditProxy {

    private final static ObjectMapper _objectMapper = new ObjectMapper();
    private static final FastDateFormat DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd' 'HH:mm:ss");
    private final Logger _logger = LoggerFactory.getLogger(this.getClass());
    private static final List<ConfigType> CONFIG_TYPES = new LinkedList<ConfigType>();
    private Map<String, String> configs = new HashMap<String, String>();
    private CloseableHttpClient httpClient = null;

    static {
        CONFIG_TYPES.add(new AddressConfig());
        CONFIG_TYPES.add(new SecretKeyConfig());
        CONFIG_TYPES.add(new TimeoutConfig());
    }

    public void setAddress(String address) {
        configs.put(AddressConfig.UUID, address);
    }

    public String getAddress() {
        return AddressConfig.getValue(configs);
    }

    public void setSecretKey(String secretKey) {
        configs.put(SecretKeyConfig.UUID, secretKey);
    }

    public String getSecretKey() {
        return SecretKeyConfig.getValue(configs);
    }

    public void setTimeout(int timeout) {
        configs.put(TimeoutConfig.UUID, String.valueOf(timeout));
    }

    public int getTimeout() {
        return TimeoutConfig.getValue(configs);
    }

    @Override
    public String getName() {
        return "月星HTTP代理";
    }

    @Override
    public void init() throws AuditProxyException {
        httpClient = HttpClients.createDefault();

    }

    @Override
    public void destroy() {
        try {
            httpClient.close();
        } catch (IOException ex) {
            _logger.error("关闭httpClient失败", ex);
        }
    }

    @Override
    public List<ConfigType> getConfigTypes() {
        return CONFIG_TYPES;
    }

    @Override
    public Map<String, String> getConfigs() {
        return configs;
    }

    @Override
    public void setConfigs(Map<String, String> configs) {
        this.configs = configs;
        for (ConfigType type : getConfigTypes()) {
            if (!this.configs.containsKey(type.getUuid())) {
                this.configs.put(type.getUuid(), type.getDefaultValue());
            }
        }
    }

    @Override
    public void auditLogin(LoginRequest request) throws AuditProxyException {
        try {
            Map<String, String> infoMap = new HashMap<String, String>();
            String nonce = UUID.randomUUID().toString();
            infoMap.put("type", "login");
            infoMap.put("userName", request.getUserName());
            String userIp = request.getUserIp() == null ? "" : request.getUserIp().getHostAddress();
            infoMap.put("userIp", userIp);
            String userMac = request.getUserMac() != null ? request.getUserMac().getAddress() : "";
            infoMap.put("userMac", userMac);
            String time = DATE_FORMAT.format(request.getTime());
            infoMap.put("time", time);

            String signature = DigestUtils.shaHex(request.getUserName() + request.getUserIp().getHostAddress() + userMac + time + nonce + getSecretKey());

            infoMap.put("nonce", nonce);
            infoMap.put("signature", signature);
            String message = _objectMapper.writeValueAsString(infoMap);
            sendMessage(message);
        } catch (IOException ex) {
            throw new AuditProxyException(ex);
        }
    }

    @Override
    public void auditLogout(LogoutRequest request) throws AuditProxyException {
        try {
            Map<String, String> infoMap = new HashMap<String, String>();
            String nonce = UUID.randomUUID().toString();
            infoMap.put("type", "logout");
            infoMap.put("userName", request.getUserName());
            String userIp = request.getUserIp() == null ? "" : request.getUserIp().getHostAddress();
            infoMap.put("userIp", userIp);
            String userMac = "";
            infoMap.put("userMac", userMac);
            String time = DATE_FORMAT.format(request.getTime());
            infoMap.put("time", time);

            String signature = DigestUtils.shaHex(request.getUserName() + request.getUserIp().getHostAddress() + userMac + time + nonce + getSecretKey());

            infoMap.put("nonce", nonce);
            infoMap.put("signature", signature);
            String message = _objectMapper.writeValueAsString(infoMap);
            sendMessage(message);
        } catch (IOException ex) {
            throw new AuditProxyException(ex);
        }
    }

    protected void sendMessage(String message) {
        CloseableHttpResponse response = null;
        try {
            SSLContext sslContext = SSLContexts.custom()
                    .loadTrustMaterial(null, new TrustStrategy() {

                        @Override
                        public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
                            return true;
                        }
                    })
                    .useTLS()
                    .build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_‌​ALL_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpPost httpPost = new HttpPost(getAddress());
            _logger.debug(message);
            httpPost.setEntity(new StringEntity(message, ContentType.create("application/json")));
            response = httpclient.execute(httpPost);
            for (String line : IOUtils.readLines(response.getEntity().getContent())) {
                _logger.debug(line);
            }
        } catch (IOException ex) {
            _logger.error("Failed to send proxy message.", ex.getMessage());
            throw new DkRuntimeException(ex);
        } catch (GeneralSecurityException ex) {
            _logger.error("Failed to send proxy message.", ex.getMessage());
            throw new DkRuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(response);
        }
    }
}
原文地址:https://www.cnblogs.com/littlehoom/p/5250003.html