httpclient

来源:互联网 发布:csgo淘宝钥匙 编辑:程序博客网 时间:2024/06/05 20:31
package tangdi.util.pos;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.inject.Named;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.conn.params.ConnPerRoute;

import sun.misc.BASE64Decoder;
import tangdi.engine.context.Etf;
import tangdi.engine.context.Log;

public class newCallMsgToRcs {
    private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    private static HttpClient client = new HttpClient(connectionManager);

    @Named("NewSendMsgToRcs")
    public static int SendMsgToRcs(@Named("SendMsgUrl") String sSendMsgUrl,
            @Named("InputNodes") String sInputNodes,
            @Named("CheckNodes") String sCheckNodes) {
        client.getParams()
                .setParameter("http.protocol.respBody-charset", "GBK");
        // 设置连接超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(
                10000);
        // 设置数据传输超时时间
        client.getHttpConnectionManager().getParams().setSoTimeout(20000);
        // 设置连接失败重试次数
        client.getHttpConnectionManager().getParams().setParameter(
                "http.method.retry-handler",
                new DefaultHttpMethodRetryHandler(2, true));
        //设置并发连接数
        client.getHttpConnectionManager().getParams()
                .setDefaultMaxConnectionsPerHost(32);
        client.getHttpConnectionManager().getParams().setMaxTotalConnections(
                256);

        PostMethod httpPost = null;
        String strResult = "";
        InputStream is = null;
        BufferedReader br = null;

        if (sSendMsgUrl == null) {
            Log.info("发送地址为空,出现错误。%s", new Object[] { sSendMsgUrl });
            return -1;
        }

        try {
            NameValuePair[] nvpPair = getNameValuePair(sInputNodes);

            String sCheckStr = getCheckStr(sCheckNodes);

            nvpPair[(nvpPair.length - 1)] = new NameValuePair("CHKVAL",
                    sCheckStr);

            StringBuffer urlString = new StringBuffer();
            for (NameValuePair item : nvpPair) {
                urlString.append(item.getName());
                urlString.append("=" + item.getValue());
                urlString.append("&");
            }

            String req_str = urlString.toString().substring(0,
                    urlString.toString().length() - 1);

            httpPost = new PostMethod(sSendMsgUrl);
            httpPost
                    .setRequestHeader(
                            "Accept",
                            "image/jpeg,application/x-ms-application,image/gif,application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*");
            httpPost.setRequestHeader("Accent-Language", "zh-CN");
            httpPost
                    .setRequestHeader(
                            "User-Agent",
                            "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; QQWubi 87; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)");
            httpPost.setRequestHeader("charset", "GBK");

            httpPost.getParams().setParameter("http.protocol.content-charset",
                    "UTF-8");

            Log.info("发送的数据地址是: " + sSendMsgUrl + "?%s",
                    new Object[] { req_str });

            httpPost.setRequestBody(nvpPair);
            httpPost.setDoAuthentication(false);

            int resultCode = client.executeMethod(httpPost);
            Etf.setChildValue("resultCode", String.valueOf(resultCode));
            Log.info("resultCode" + String.valueOf(resultCode), new Object[0]);
            String returnString = "";
            if (resultCode == 200) {

                is = httpPost.getResponseBodyAsStream();

                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line = null;
                String resultDate = "";
                while ((line = br.readLine()) != null) {
                    resultDate = resultDate + line;
                }
                JSONObject sobj = new JSONObject();
                sobj = JSONObject.fromObject(resultDate.toString());
                Log.info("sobj" + sobj, new Object[0]);
                String result = sobj.getString("RESULT");
                Etf.setChildValue("result", result);
                String cardname = sobj.getString("CARDNAME");
                String cardno = sobj.getString("CARDNO");
                String photo = sobj.getString("PHOTO");
                if (result.equals("0")) {
                    strResult = strResult + "身份证号码合法";
                    long photo_s = System.currentTimeMillis();
                    Log.info("strResult" + strResult, new Object[0]);
                    Log.info("result" + result, new Object[0]);
                    Log.info("cardname" + cardname, new Object[0]);
                    Log.info("cardno" + cardno, new Object[0]);
                    Log.info("photo" + photo, new Object[0]);
                    Log.info("photo_s" + photo_s + cardno, new Object[0]);
                    Etf.setChildValue("photos", photo_s + cardno);
                    Etf.setChildValue("identity_name", photo_s + cardno + "_"
                            + cardname + ".jpg");
                    GenerateImage(photo,
                            "/usr/local/pos/resin-pro-4.0.25/webapps/posw/upload/identity/"
                                    + photo_s + cardno + "_" + cardname
                                    + ".jpg");
                } else if (result.equals("1")) {
                    strResult = strResult + "姓名与身份证号码不一致";
                    Log.info("strResult" + strResult, new Object[0]);
                } else {
                    strResult = strResult + "无此身份证号码";
                    Log.info("strResult" + strResult, new Object[0]);
                }
                Log
                        .info(" 接收到的返回数据:%s", new Object[] { resultDate
                                .toString() });
                br.close();
                is.close();
                return 0;
            }

            Log.info(" 接收到的返回数据:%s", new Object[] { "请求返回出现问题!" });
            Log.info("发送信息失败:", new Object[] { resultCode + " : "
                    + returnString });
            return -1;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Log.info("关闭httpPost:", new Object[] {});
            httpPost.releaseConnection();
            Log.info("关闭httpClient:", new Object[] {});
            client.getHttpConnectionManager().closeIdleConnections(0);
            if (br != null) {
                try {
                    Log.info("关闭br:", new Object[] {});
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    Log.info("关闭is:", new Object[] {});
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return -1;
    }

    public static String getCheckStr(String sCheckNodes) {
        String[] arrParams = getArrBySplit(sCheckNodes, ",");
        String sRes = "";
        String sUpper = null;
        String sTemp = null;

        for (String sNodesName : arrParams) {
            sUpper = sNodesName.toUpperCase();
            if (Etf.getChildValue(sUpper) != null)
                sTemp = Etf.getChildValue(sUpper);
            else {
                sTemp = "";
            }
            sRes = sRes + sTemp;
        }

        sRes = digest(sRes, "UTF-8");

        return sRes;
    }

    public static NameValuePair[] getNameValuePair(String sInputNodes) {
        String[] arrParams = getArrBySplit(sInputNodes, ",");
        NameValuePair[] resNameValuePair = new NameValuePair[arrParams.length + 1];
        String sTemp = null;
        String sUpper = null;
        String sNodesName = null;
        for (int i = 0; i < arrParams.length; ++i) {
            sNodesName = arrParams[i];
            sUpper = sNodesName.toUpperCase();
            if (Etf.getChildValue(sUpper) != null)
                sTemp = Etf.getChildValue(sUpper);
            else {
                sTemp = "";
            }
            Log.info(sUpper + "  " + sTemp, new Object[0]);
            resNameValuePair[i] = new NameValuePair(sUpper, sTemp);
        }
        return resNameValuePair;
    }

    public static String[] getArrBySplit(String sStr, String split) {
        String[] sArr = (String[]) null;
        if ((sStr == null) || ("".equals(sStr)))
            sArr = new String[0];
        else {
            sArr = sStr.split(split);
        }
        return sArr;
    }

    public static String digest(String aValue, String encoding) {
        aValue = aValue.trim();
        byte[] value;
        try {
            value = aValue.getBytes(encoding);
        } catch (UnsupportedEncodingException e) {
            value = aValue.getBytes();
        }
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return toHex(md.digest(value));
    }

    public static String toHex(byte[] input) {
        if (input == null)
            return null;
        StringBuffer output = new StringBuffer(input.length * 2);
        for (int i = 0; i < input.length; ++i) {
            int current = input[i] & 0xFF;
            if (current < 16)
                output.append("0");
            output.append(Integer.toString(current, 16));
        }

        return output.toString();
    }

    public static boolean GenerateImage(String imgStr, String imgFilePath) {
        if (imgStr == null)
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    int tmp36_34 = i;
                    byte[] tmp36_33 = bytes;
                    tmp36_33[tmp36_34] = (byte) (tmp36_33[tmp36_34] + 256);
                }
            }
            out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception localException) {
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {

    }
}
0 0
原创粉丝点击