HttpClient系列-Post使用基础知识

简述

本文学习如何简单的使用POST,如何上传文件等等场景

基础POST

首先,让我们来看一个简单的例子,并使用HttpClient发送POST请求。

我们将使用两个参数 - “username”和“password” 进行POST :

@Test
public void test() 
  throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", "John"));
    params.add(new BasicNameValuePair("password", "pass"));
    httpPost.setEntity(new UrlEncodedFormEntity(params));
 
    HttpPost httpPost = new HttpPost("http://localhost:8080");

    CloseableHttpResponse response = client.execute(httpPost);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}

请注意我们如何使用List<NameValuePair>在POST请求中包含参数。

使用授权进行POST

接下来,让我们看看如何使用HttpClient对身份验证凭据进行POST 。

在以下示例中 - 我们通过添加Authorization在Header向使用基本身份验证保护的URL发送POST请求:

@Test
public void test()
  throws ClientProtocolException, IOException, AuthenticationException {
    CloseableHttpClient client = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:8080");


   httpPost.setEntity(new StringEntity("test post"));
    UsernamePasswordCredentials creds
      = new UsernamePasswordCredentials("John", "pass");
    httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
 
    CloseableHttpResponse respo
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值