2种方式
方式一:Http请求头上添加Basic Authentication认证
// httpPost
httpPost.addHeader(“Authorization”, "Basic " + Base64.encodeBase64String(“username:password”.getBytes()));
// httpConnection
httpConn.setRequestProperty(“Authorization”, "Basic " + Base64.encodeBase64String(“username:password”.getBytes()));
方式二:使用Authenticator重写getPasswordAuthentication()–无测试过
相关jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.Closeabl

本文介绍了两种在Java中实现HTTP Basic Authentication的方法,包括直接在HTTP请求头中添加认证信息和使用Authenticator。同时,代码展示了如何设置代理进行HTTP Post请求,并处理了相关异常。
最低0.47元/天 解锁文章
1178

被折叠的 条评论
为什么被折叠?



