HttpClient配置及运用

什么是HttpClient?

 官方的解释是:HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

其实就是可以连接http的工具.

.接下来看一下代码:

public class HttpHelper {

	public static JSONObject httpGet(String url) throws GetAccessToken.OapiException,IOException {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();//创建实例
//CloseableHttpClient意思是:可关闭的
        RequestConfig requestConfig = RequestConfig.custom().
        		setSocketTimeout(60000).setConnectTimeout(60000).build();
        httpGet.setConfig(requestConfig);
        try {
//执行
            response = httpClient.execute(httpGet, new BasicHttpContext());
            if (response.getStatusLine().getStatusCode() != IntConstantEnum.HTTP_HELP.getValue()) {

                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
                                   + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                JSONObject result = JSON.parseObject(resultStr);
                if (result.getInteger(StringConstantEnum.HTTP_HELP.getValue()) == 0) {
                    return result;
                } else {
                    System.out.println("request url=" + url + ",return value=");
                    System.out.println(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new GetAccessToken.OapiException(errCode, errMsg);
                }
            }
        } catch (IOException e) {
 //客户端协议异常
            log.error("调用接口获取数据失败",e);
            throw new RuntimeException(e);
        } finally {
            if (response != null) {
                response.close();
            }
        }

        return null;
    }
	
	
	public static JSONObject httpPost(String url, Object data) throws GetAccessToken.OapiException,IOException{
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().
        		setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json");

        try {
//4、获取实体
        	StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
            httpPost.setEntity(requestEntity);
            response = httpClient.execute(httpPost, new BasicHttpContext());
            if (response.getStatusLine().getStatusCode() != IntConstantEnum.HTTP_HELP.getValue()) {
                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
                                   + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                JSONObject result = JSON.parseObject(resultStr);
                if (result.getInteger(StringConstantEnum.HTTP_HELP.getValue()) == 0) {
                	result.remove("errcode");
                	result.remove("errmsg");
                    return result;
                } else {
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new GetAccessToken.OapiException(errCode, errMsg);
                }
            }
        } catch (IOException e) {
            log.error("调用钉钉接口获取数据失败",e);
            throw e;
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }


    public static void main(String[] args) {

//	    String accessToken=getAccessToken();
//        System.out.println("token====>"+accessToken);

        String signature=getSigature();

	    String url="https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=dingoa3jigjmsp7lkv7th1&timestamp="+System.currentTimeMillis()+"&signature="+signature;

	    String result=null;
	    String json=null;
	    try {
            // 创建httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();

            HttpPost httpPost = new HttpPost(url);
            Map<String,Object> map=new HashMap<>();
            map.put("tmpAuthCode","4a2c5695b78738d495f47b5fee9160cd");

            json= JsonUtil.mapToJson(map,true);
            // 设置参数到请求对象中
            StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            stringEntity.setContentEncoding("utf-8");
            httpPost.setEntity(stringEntity);

            CloseableHttpResponse response = httpClient.execute(httpPost);

            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(result);
            }
            // 释放链接
            response.close();
        }catch (IOException e){
	        throw new RuntimeException(e);
        }

    }

    public static String getSigature(){
	    String appSecret="...";
        // 根据timestamp, appSecret计算签名值
        String urlEncodeSignature=null;
        try {
            String stringToSign = String.valueOf(System.currentTimeMillis());
            Mac mac = Mac.getInstance("...");
            mac.init(new SecretKeySpec(appSecret.getBytes("utf-8"), "..."));
            byte[] signatureBytes = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String signature = new String( Base64.encodeBase64(signatureBytes));
            urlEncodeSignature = urlEncode(signature);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return urlEncodeSignature;
    }

    // encoding参数使用utf-8
    public static String urlEncode(String value) {
        if (value == null) {
            return "";
        }
        try {
            String encoded = URLEncoder.encode(value,"UTF-8");
            return encoded.replace("+", "%20").replace("*", "%2A")
                    .replace("~", "%7E").replace("/", "%2F");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("FailedToEncodeUri", e);
        }
    }

    public static String getAccessToken() {
        String appkey="ding4send81blzjzclre";
        String appsecret="...";

        JSONObject accesstoken = null;
        String accesstoken2 = "";
        String urlaccesstoken = "...;
        try {
            accesstoken = HttpHelper.httpGet(urlaccesstoken);
            JSONObject accesstoken1 = new JSONObject(accesstoken);
            accesstoken2 = (String) accesstoken1.get("access_token");
        } catch (GetAccessToken.OapiException e) {
            log.error("调用接口异常--获取accesstoken失败:...);
            throw new RuntimeException(e);
        } catch (IOException ioe){
            log.error("IO异常--获取accesstoken失败:-{}:corpid,-{}corpsecret,-{}accesstoken,-{}accesstoken2",appkey,appsecret,accesstoken,accesstoken2);
            throw new RuntimeException(ioe);
        }
        return accesstoken2;
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值