HttpClient post 请求第三方接口 basic auth

public class TestConnection {

    public static String httpClientWithBasicAuth() {



        String username="xxx";
        String password="xxx";
        String uri="xxxx";

        Map<String, String> paramMap = new HashMap<String,String>();
        paramMap.put("xxx", "xxxx");

        String result = "";
        try {
            // 创建HttpClientBuilder
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            //绕过证书
            CloseableHttpClient closeableHttpClient = httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .build();

            HttpPost httpPost = new HttpPost(uri);

            //String a = Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes());
            //添加http头信息
            httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
            httpPost.addHeader("Content-Type", "application/json");
            //httpPost.addHeader("Authorization","Basic "+a);

            StringEntity s = new StringEntity(JSON.toJSONString(paramMap));
            s.setContentEncoding("UTF-8");
            httpPost.setEntity(s);


            HttpResponse httpResponse = null;
            HttpEntity entity = null;
            try {
                httpResponse = closeableHttpClient.execute(httpPost);
                entity = httpResponse.getEntity();
                System.out.println("httpResponse==="+httpResponse.getStatusLine());
                if( entity != null ){
                    result = EntityUtils.toString(entity);
                    System.out.println("result===="+result);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 关闭连接
            closeableHttpClient.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) throws Throwable {

        httpClientWithBasicAuth();
    }
}

 

maven引用的依赖包:

<dependencies>
   <dependency>
      <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <version>4.5.3</version>
   </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5</version>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>

</dependencies>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值