java发送带Basic Auth认证的httpGet请求实例代码

一、APIPOST测试

java发送带Basic Auth认证的http请求实例代码

Base64加密方式认证方式下的basic auth。

请添加图片描述

二、导入pom文件

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

三、代码实例

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

httpClient方法
public static String doGet(String urlStr){
    // 创建HttpClientBuilder
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    // 设置BasicAuth
    CredentialsProvider provider = new BasicCredentialsProvider();
    // Create the authentication scope
    AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    // Create credential pair,在此处填写用户名和密码
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("root", "123456");
    // Inject the credentials
    provider.setCredentials(scope, credentials);
    // Set the default credentials provider
    httpClientBuilder.setDefaultCredentialsProvider(provider);
    // HttpClient
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

    String result = "";
    HttpGet httpGet = null;
    HttpResponse httpResponse = null;
    HttpEntity entity = null;
    httpGet = new HttpGet(urlStr);
    try {
        httpResponse = closeableHttpClient.execute(httpGet);
        entity = httpResponse.getEntity();
        if( entity != null ){
            result = EntityUtils.toString(entity);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 关闭连接
    try {
        closeableHttpClient.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    //
    System.out.println(result);
    return result;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值