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

爱学习饼 CTO  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
...全文
144 点赞 收藏 回复
写回复
回复
切换为时间正序
请发表友善的回复…
发表回复

还没有回复,快来抢沙发~

发动态
发帖子
Web 开发
创建于2007-09-28

7.9w+

社区成员

Java Web 开发
申请成为版主
社区公告
暂无公告