HttpClientUtis 工具类

package com.cross.bridge.prerecord.util;

import com.cross.bridge.prerecord.dto.ResultDto;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.UUID;

/**
 * @Describe: HttpClientUtis 工具类
 * @Author: Bridge
 * @Date: 2018/5/15
 * @Version: 1.00
 */
public class HttpClientUtis {
    /** 声明 **/
    private static String nonce = RandomStringUtils.randomAlphanumeric(10);
    /** 时间戳 **/
    private static int timestamp = (int) (System.currentTimeMillis() / 1000);

    /**
     *检测用户
     * GET请求
     * @return
     */
    public static String  detectionAccount(){
        String hmacUrl = "/passp/v2/oauth/checkname/13523416655?nonce="+nonce+"&timestamp="+timestamp+"GET";
        byte[] hmac = HmacUtils.hmacSHA512(hmacUrl.getBytes(), SECRET_KEY);
        String finalResult = HmacUtils.base64Url(hmac);
        CloseableHttpClient httpCilent = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)   //设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//默认允许自动重定向
                .build();
        HttpGet httpGet = new HttpGet("https://api.e-k.com.cn/passp/v2/oauth/checkname/13523416655");
        System.out.println(finalResult);
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("ClientApp-ID",""+ID+"");
        httpGet.setHeader("ClientApp-Ver",""+VER+"");
        httpGet.setHeader("Authorization",""+AUTHORIZATION+" "+nonce+";"+timestamp+";"+finalResult+"");
        httpGet.setHeader("User-Agent",""+AGENT+"");
        return getHttpResponseResult(httpCilent,null,httpGet);

    }

    /**
     * 登陆
     * POST请求
     * @return
     */
    public static String  usersLogin(ResultDto userDto){
        //密码签名
        String newPassword = PASSWORD + userDto.getSalt();
        String pwdBase64 = HmacUtils.base64(HmacUtils.sha512(newPassword));
        byte[] signHash = HmacUtils.hmacSHA512(userDto.getKey().getBytes(),pwdBase64);
        String encryptedPWD = HmacUtils.base64(signHash);

        //签名生成
        String hmacUrl = "/passp/v2/oauth?nonce=" + nonce + "&timestamp=" + timestamp + "POST{\"userCode\":\""+USERCODE+"\",\"encryptedPWD\":[{\"encryptedPWD\":\"" + encryptedPWD + "\",\"orgCode\":\""+ userDto.getOrgCode()+"\"}]}";
        byte[] hmac = HmacUtils.hmacSHA512(hmacUrl.getBytes(), SECRET_KEY);
        String finalResult = HmacUtils.base64Url(hmac);

        CloseableHttpClient httpCilent = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)   //设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//默认允许自动重定向
                .build();
        HttpPost httpPost = new HttpPost("https://api.e-k.com.cn/passp/v2/oauth");// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("ClientApp-ID", ""+ID+"");
        httpPost.setHeader("ClientApp-Ver", ""+VER+"");
        httpPost.setHeader("Authorization", ""+AUTHORIZATION+" " + nonce + ";" + timestamp + ";" + finalResult + "");
        httpPost.setHeader("User-Agent", ""+AGENT+"");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity("{\"userCode\":\""+USERCODE+"\",\"encryptedPWD\":[{\"encryptedPWD\":\"" + encryptedPWD + "\",\"orgCode\":\""+ userDto.getOrgCode()+"\"}]}", charSet);
        httpPost.setEntity(entity);
        return getHttpResponseResult(httpCilent,httpPost,null);
    }

    /**
     * 使用进港信息采集接口前,需要用已有的管理员组的账户调用登录接口登录,并获取到Access_Token
     * @param jsonData  请求的JSON对象数据
     * @param expAndToken 时间戳和ToKen信息
     * @return
     */
    public static String detectionAccessToken(String jsonData,ResultDto expAndToken){
        //业务流水号
        String businessNumber = UUID.randomUUID().toString();
        String hmacUrl = "/eclp/edi/channel/costco/term/W4/sid/"+businessNumber+"?nonce="+nonce+"&timestamp="+timestamp+"" + "POST"+jsonData+"";
        //签名生成
        byte[] hmac = HmacUtils.hmacSHA512(hmacUrl.getBytes(), SECRET_KEY);
        String finalResult = HmacUtils.base64Url(hmac);
        CloseableHttpClient httpCilent = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)   //设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//默认允许自动重定向
                .build();
        HttpPost httpPost = new HttpPost("https://api.e-k.com.cn/eclp/edi/channel/costco/term/W4/sid/"+businessNumber+"");// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("ClientApp-ID", ""+ID+"");
        httpPost.setHeader("ClientApp-Ver", ""+VER+"");
        httpPost.setHeader("Authorization", ""+AUTHORIZATION+" " + nonce + ";" + timestamp + ";" + finalResult + "");
        httpPost.setHeader("User-Agent", ""+AGENT+"");
        httpPost.setHeader("X-ApiName",""+APINAME+"");
        httpPost.setHeader("Access-Token",""+expAndToken.getToken()+"");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(""+jsonData+"", charSet);
        httpPost.setEntity(entity);
        return getHttpResponseResult(httpCilent,httpPost,null);
    }

    /**
     * 获取出 httpCilent 响应的结果
     * @param httpCilent
     * @param httpPost
     * @param httpGet
     * @return
     */
    public static String getHttpResponseResult(CloseableHttpClient httpCilent,HttpPost httpPost,HttpGet httpGet){
        String srtResult = "";
        HttpResponse httpResponse = null;
        try {
            if(null != httpPost){
                httpResponse = httpCilent.execute(httpPost);
            }
            if(null != httpGet){
                httpResponse = httpCilent.execute(httpGet);
            }
            if(null != httpResponse){
                if(httpResponse.getStatusLine().getStatusCode() == 200){
                    srtResult = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");//获得返回的结果
                }else{
                    srtResult = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
                }
            }else{
                srtResult = "请求参数不能为空!";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpCilent.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return srtResult;
    }

    /**
     * 获取检测用户中的key秘钥
     * @param jsonData
     * @return
     */
    public static ResultDto getAccountOrKey(String jsonData){
        ResultDto userDto = new ResultDto();
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            String data = jsonObject.getString("data");
            JSONArray jsonArray = new JSONArray(data);
            if(null != jsonArray && jsonArray.length() != 0){
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject key = (JSONObject) jsonArray.get(i);
                    userDto.setOrgName(key.getString("orgName"));
                    userDto.setOrgCode(key.getString("orgCode"));
                    userDto.setSalt(key.getString("salt"));
                    userDto.setKey(key.getString("key"));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return userDto;
    }

    /**
     * 获取登录成功的时间戳和Token信息
     * @param jsonData
     * @return
     */
    public static ResultDto getExpAndToken(String jsonData){
        ResultDto userDto = new ResultDto();
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            String data = jsonObject.getString("data");
            JSONObject dataObject = new JSONObject(data);
            if(null != dataObject && !"".equals(dataObject)){
                userDto.setExp(dataObject.getString("exp"));
                userDto.setToken(dataObject.getString("token"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return userDto;
    }


}

转载于:https://my.oschina.net/u/3854850/blog/1818873

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值