码迷,mamicode.com
首页 > Web开发 > 详细

HTTPS请求

时间:2016-03-07 13:33:03      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

 

/*
 * 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请求

标签:

原文地址:http://www.cnblogs.com/littlehoom/p/5250003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!