httpClient发送post请求

时间:2022-10-29 21:09:29
/*
 * 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.generichttp;

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 java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author zxf
 */
public class GenericHttpProxy 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> map = new HashMap<String, String>();
            long timestamp = Calendar.getInstance().getTimeInMillis();
            byte[] nonceBytes = new byte[16];
            new Random().nextBytes(nonceBytes);
            String nonce = Hex.encodeHexString(nonceBytes);
            map.put("type", "login");
            map.put("userName", request.getUserName());
            map.put("userIp", request.getUserIp().getHostAddress());
            if (request.getUserMac() != null) {
                map.put("userMac", request.getUserMac().getAddress());
            }
            String time = DATE_FORMAT.format(request.getTime());
            map.put("time", time);
            String info = _objectMapper.writeValueAsString(map);
            String signature = DigestUtils.shaHex(info + timestamp + nonce + getSecretKey());

            sendMessage(info, timestamp, nonce, signature);
        } catch (IOException ex) {
            throw new AuditProxyException(ex);
        }
    }

    @Override
    public void auditLogout(LogoutRequest request) throws AuditProxyException {
        try {
            Map<String, String> map = new HashMap<String, String>();
            long timestamp = Calendar.getInstance().getTimeInMillis();
            byte[] nonceBytes = new byte[16];
            new Random().nextBytes(nonceBytes);
            String nonce = Hex.encodeHexString(nonceBytes);
            map.put("type", "logout");
            map.put("userName", request.getUserName());
            map.put("userIp", request.getUserIp().getHostAddress());
            if (request.getUserMac() != null) {
                map.put("userMac", request.getUserMac().getAddress());
            }
            String time = DATE_FORMAT.format(request.getTime());
            map.put("time", time);
            String info = _objectMapper.writeValueAsString(map);
            String signature = DigestUtils.shaHex(info + timestamp + nonce + getSecretKey());
            sendMessage(info, timestamp, nonce, signature);
        } catch (IOException ex) {
            throw new AuditProxyException(ex);
        }
    }

    protected void sendMessage(String info, long timestamp, String nonce, String signature) throws IOException {
        CloseableHttpResponse response = null;
        try {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("info", info));
            nvps.add(new BasicNameValuePair("timestamp", String.valueOf(timestamp)));
            nvps.add(new BasicNameValuePair("nonce", nonce));
            nvps.add(new BasicNameValuePair("signature", signature));
            HttpPost httpPost = new HttpPost(getAddress());
            httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(getTimeout() * 1000)
                    .setConnectTimeout(getTimeout() * 1000)
                    .build());
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            _logger.error(e.getMessage());
            throw new IOException(e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}