httpclient post/get with http basic authentication

背景描述

项目中API网关用到了http basic authentication
auth用户名为特定用户的帐号密码,使用RSA加密之后得到的密文,无需设置密码
在测试的过程中,需要调用GET POST方法,普通方法无法通过校验,故自己写了个简单的类

代码

完整代码

https://github.com/hisenyuan/IDEAPractice/blob/master/src/main/java/com/hisen/utils/HttpClientUtil.java

GET方法with auth

    /**
     * get with http basic auth
     */
    public static String sendGetWithAuth(String url, Map data, String auth) {
        String responseContent = null;
        try {
            // auth
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(auth, "");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
                    .build();
            // form data
            url = url + "?" + getGetParamByMap(data);
            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            // get process
            CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpGet);
            LOGGER.info("http respone code:" + response.getStatusLine().getStatusCode());
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
            LOGGER.info("http respone data:" + responseContent);
            // close resources
            response.close();
            ((CloseableHttpClient) client).close();
        } catch (Exception e) {
            LOGGER.error("send post error", e);
        }
        return responseContent;
    }

普通GET方法

    public static String sendGet(String url, Map data, Map header) {
        String responseContent = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();
            url = url + "?" + getGetParamByMap(data);
            HttpGet httpGet = new HttpGet(url);
            // add header
            if (!header.isEmpty()) {
                header.entrySet().stream().forEach(
                        entry -> httpGet.addHeader(entry.getKey(), entry.getValue()));
            }
            // get process
            CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpGet);
            LOGGER.info("http respone code:" + response.getStatusLine().getStatusCode());
            HttpEntity resEntity = response.getEntity();
            responseContent = EntityUtils.toString(resEntity, "UTF-8");
            LOGGER.info("http respone data:" + responseContent);
            // close resources
            response.close();
            ((CloseableHttpClient) client).close();
        } catch (Exception e) {
            LOGGER.error("send get error", e);
        }
        return responseContent;
    }

你可能感兴趣的:(httpclient post/get with http basic authentication)