HttpClient使用介绍

使用HttpClient发送请求主要分为以下几步骤:
  • 创建 CloseableHttpClient对象或CloseableHttpAsyncClient对象,前者同步,后者为异步
  • 创建Http请求对象
  • 调用execute方法执行请求,如果是异步请求在执行之前需调用start方法
创建连接:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();

该连接为同步连接

GET请求:
@Test
public void testGet() throws IOException {
    String api = "/api/getUri";
    String url = String.format("%s%s", BASE_URL, api);
    HttpGet httpGet = new HttpGet(url);
    CloseableHttpResponse response = httpClient.execute(httpGet);
    System.out.println(EntityUtils.toString(response.getEntity()));
}

使用HttpGet表示该连接为GET请求,HttpClient调用execute方法发送GET请求

PUT请求:
@Test
public void testPut() throws IOException {
    String api = "/api/putUri";
    String url = String.format("%s%s", BASE_URL, api);
    HttpPut httpPut = new HttpPut(url);
    UserVO userVO = UserVO.builder().name("h2t").id(16L).build();
    httpPut.setHeader("Content-Type", "application/json;charset=utf8");
    httpPut.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));
    CloseableHttpResponse response = httpClient.execute(httpPut);
    System.out.println(EntityUtils.toString(response.getEntity()));
}
POST请求:

添加对象

@Test
public void testPost() throws IOException {
    String api = "/api/postUri";
    String url = String.format("%s%s", BASE_URL, api);
    HttpPost httpPost = new HttpPost(url);
    UserVO userVO = UserVO.builder().name("h2t2").build();
    httpPost.setHeader("Content-Type", "application/json;charset=utf8");
    httpPost.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));
    CloseableHttpResponse response = httpClient.execute(httpPost);
    System.out.println(EntityUtils.toString(response.getEntity()));
}

该请求是一个创建对象的请求,需要传入一个json字符串
上传文件

@Test
public void testUpload1() throws IOException {
    String api = "/api/postUri/file";
    String url = String.format("%s%s", BASE_URL, api);
    HttpPost httpPost = new HttpPost(url);
    File file = new File("C:/Users/hetiantian/Desktop/学习/docker_practice.pdf");
    FileBody fileBody = new FileBody(file);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("file", fileBody);  //addPart上传文件
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);
    CloseableHttpResponse response = httpClient.execute(httpPost);
    System.out.println(EntityUtils.toString(response.getEntity()));
}

通过addPart上传文件

DELETE请求:
@Test
public void testDelete() throws IOException {
    String api = "/api/delete";
    String url = String.format("%s%s", BASE_URL, api);
    HttpDelete httpDelete = new HttpDelete(url);
    CloseableHttpResponse response = httpClient.execute(httpDelete);
    System.out.println(EntityUtils.toString(response.getEntity()));
}
请求的取消:
@Test
public void testCancel() throws IOException {
    String api = "/api/cancel";
    String url = String.format("%s%s", BASE_URL, api);
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);  //设置超时时间
    //测试连接的取消

    long begin = System.currentTimeMillis();
    CloseableHttpResponse response = httpClient.execute(httpGet);
    while (true) {
        if (System.currentTimeMillis() - begin > 1000) {
          httpGet.abort();
          System.out.println("task canceled");
          break;
      }
    }

    System.out.println(EntityUtils.toString(response.getEntity()));
}

调用abort方法取消请求 执行结果:

task canceled
cost 8098 msc
Disconnected from the target VM, address: '127.0.0.1:60549', transport: 'socket'

java.net.SocketException: socket closed...【省略】
超时设置

HttpClient超时设置:
在HttpClient4.3+版本以上,超时设置通过RequestConfig进行设置

private CloseableHttpClient httpClient = HttpClientBuilder.create().build();
private RequestConfig requestConfig =  RequestConfig.custom()
        .setSocketTimeout(60 * 1000)
        .setConnectTimeout(60 * 1000).build();
String api = "/api/timeOut";
String url = String.format("%s%s", BASE_URL, api);
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);  //设置超时时间

超时时间是设置在请求类型HttpGet上,而不是HttpClient上

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值