获取依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <repositories> <repository> <id>github-maven-repo</id> <url>https://raw.github.com/fanlychie/maven-repo/releases</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.fanlychie</groupId> <artifactId>commons-httpclient</artifactId> <version>1.0.2</version> </dependency> </dependencies>
|
环境要求
JDK1.8 或以上版本
项目地址
https://github.com/fanlychie/commons-httpclient
GET 请求
1 2 3 4 5 6 7 8 9 10
| HttpClientUtils.get("http://huaban.com/search/") .addParameter("q", "2017") .addParameter("sort", "created_at") .execute((statusCode, responseText) -> { });
|
参数 |
类型 |
描述 |
statusCode |
int |
响应的状态码值 |
responseText |
string |
响应的文本内容 |
完整示例 ( GET/PUT/POST/DELETE 拥有同样的配置项 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| HttpClientUtils.get("http://huaban.com/search/") .addParameter("q", "2017") .addParameter("sort", "created_at") .addHeader("arg", "value") .setContentEncoding("UTF-8") .setConnectTimeout(30 * 1000) .setReadTimeout(3 * 60 * 1000) .setRetryTimes(3) .setHttpProxy("116.226.136.135", 8118) .execute((statusCode, responseText) -> { });
|
DELETE 请求
1 2 3 4 5 6 7 8 9 10
| HttpClientUtils.delete("http://domain.com") .addParameter("arg1", "value1") .addParameter("arg2", "value2") .execute((statusCode, responseText) -> { });
|
POST 请求
普通表单提交
键值对参数:
1 2 3 4 5 6 7 8 9 10
| HttpClientUtils.post("http://domain.com") .addParameter("arg1", "value1") .addParameter("arg2", "value2") .execute((statusCode, responseText) -> { });
|
JSON 参数:
1 2 3 4 5 6 7 8
| HttpClientUtils.post("http://domain.com") .addJSONParameter("{\"arg1\":\"value1\",\"arg2\":\"value2\"}") .execute((statusCode, responseText) -> { });
|
文件上传表单
1 2 3 4 5 6 7 8 9 10 11 12
| HttpClientUtils.postMultipartForm("http://domain.com") .addParameter("arg1", "value1") .addParameter("arg2", "value2") .addParameter("file", new File("pom.xml")) .execute((statusCode, responseText) -> { });
|
PUT 请求
普通表单提交
键值对参数:
1 2 3 4 5 6 7 8 9 10
| HttpClientUtils.put("http://domain.com") .addParameter("arg1", "value1") .addParameter("arg2", "value2") .execute((statusCode, responseText) -> { });
|
JSON 参数:
1 2 3 4 5 6 7 8
| HttpClientUtils.put("http://domain.com") .addJSONParameter("{\"arg1\":\"value1\",\"arg2\":\"value2\"}") .execute((statusCode, responseText) -> { });
|
文件上传表单
1 2 3 4 5 6 7 8 9 10 11 12
| HttpClientUtils.putMultipartForm("http://domain.com") .addParameter("arg1", "value1") .addParameter("arg2", "value2") .addParameter("file", new File("pom.xml")) .execute((statusCode, responseText) -> { });
|
调试日志
1
| log4j.logger.org.fanlychie.commons.httpclient = DEBUG
|