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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/285299.html
標籤:Web 開發