zhttp,我开发的一个简化httpcomponents操作的工具

爱学习饼 2021-05-27 11:09:39
zhttp是一个封装了httpcomponents的工具,用于简化httpcomponents的操作。

用httpcomponents发送一个get请求,至少需要这样:


CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);

// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

private HttpResponse response;

@Override
public String handleResponse(final HttpResponse response) throws IOException {
this.response = response;
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity, "UTF-8") : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}

};
String responseBody;
try {
responseBody = httpClient.execute(httpGet, responseHandler);
} catch (IOException e) {
throw new HttpUtilsException("Get from " + url + " error.", e);
} finally {
httpClient.close();
}


用zhttp封装后,现在发送一个get请求,只需要以下几步:


BasicHttpUtils basicHttpUtils = new BasicHttpUtils(String.class, url);

String responseBody;
try {
responseBody = (String) basicHttpUtils.get();
} catch (HttpUtilsException e) {
throw new ServiceException("Get from " + url + " error.", e);
} catch (IOException e) {
throw new ServiceException("Get from " + url + " error.", e);
}


zhttp还提供了发送post请求、下载文件、发送带Authorization Header的HTTP请求、在请求体中带上表单数据、在请求体中带上文本或json数据等功能。

详情请移步zhttp的开源项目地址:https://gitee.com/zhu-yinli/zhttp
...全文
205 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧