Apache HttpClient示例– CloseableHttpClient

Apache HttpClient can be used to send HTTP requests from client code to server. In our last tutorial, we saw how to use HttpURLConnection to perform GET and POST HTTP request operations from java program itself. Today we will take the same example project but use Apache HttpClient to perform GET and POST request operations.

Apache HttpClient可用于将HTTP请求从客户端代码发送到服务器。 在上一教程中,我们了解了如何使用HttpURLConnection从Java程序本身执行GET和POST HTTP请求操作。 今天,我们将使用相同的示例项目,但是使用Apache HttpClient执行GET和POST请求操作。

Apache HttpClient (Apache HttpClient)

For the sake of understanding the GET and POST request details, I would strongly suggest you to have a look at the earlier example too. Apache HttpClient is very widely used for sending HTTP requests from java program itself. If you are using Maven, then you can add below dependencies and it will include all other required dependencies for using Apache HttpClient.

为了理解GET和POST请求的详细信息,我强烈建议您也看一下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基本的Apache HttpClient身份验证示例: ```java 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.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientBasicAuthExample { public static void main(String[] args) throws IOException { // 创建凭据提供程序 CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("username", "password"); provider.setCredentials(AuthScope.ANY, credentials); // 创建 HttpClient 实例 CloseableHttpClient httpClient = HttpClients.custom() .setDefaultCredentialsProvider(provider) .build(); // 创建 HTTP GET 请求 HttpGet httpGet = new HttpGet("https://example.com"); // 执行请求 HttpResponse response = httpClient.execute(httpGet); // 打印响应 HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseString); // 关闭 HttpClient 实例 httpClient.close(); } } ``` 在这个示例中,我们首先创建了一个凭据提供程序,并设置了用户名和密码。然后,我们使用凭据提供程序创建了一个 HttpClient 实例。接下来,我们创建了一个 HTTP GET 请求,并使用 HttpClient 实例执行了该请求。最后,我们从响应实体中获取了响应内容,并关闭了 HttpClient 实例。请注意,我们将字符集设置为“UTF-8”,以便正确读取响应内容。 请注意,这只是一个基本示例,请根据您的实际需求进行修改。例如,您可以使用不同的身份验证方案(如摘要身份验证、NTLM身份验证等),或者使用不同的请求方法(如POST、PUT等)。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值