一、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;
}