Apache HttpComponents 简单使用
文章目录
官网
参考 https://www.cnblogs.com/lrzy/articles/15667814.html
- 网络编程(含 UrlConnection 发送 HTTP 请求下载文件):https://blog.csdn.net/qq_41538097/article/details/118722718
- Apache HttpComponents 简单使用:https://blog.csdn.net/qq_41538097/article/details/123719298
- RestTemplate简单使用:https://blog.csdn.net/qq_41538097/article/details/123560238
- okhttp3简单使用:https://blog.csdn.net/qq_41538097/article/details/123677614
- HttpURLConnection 简单使用:https://blog.csdn.net/qq_41538097/article/details/123697432
一、简介
Apache Commons HttpClient(或被称为 Apache HttpClient 3.x)、Apache HttpComponents Client(或被称为 Apache HttpClient 4.x)
HttpComponents 项目就是专门设计来简化 HTTP 客户端与服务器进行各种通讯编程。
现在的 HttpComponents 包含多个子项目
HttpComponents Core、HttpComponents Client、HttpComponents AsyncClient、Commons HttpClient
主要的功能
- 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
- 支持自动转向
- 支持 HTTPS 协议
- 支持代理服务器等
- 支持Cookie
1、导入依赖
最新版本 4.5.13
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
请求地址:http://127.0.0.1:8080/HttpClient/get/params?id=123456&name=admin
@Autowired
HttpClientComponentsController httpClientComponentsController;
@Test
public void getMethod() throws IOException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", 123456);
jsonObject.put("name", "admin");
StringBuilder url = new StringBuilder("http://127.0.0.1:8080/HttpClient/get/params");
url.append("?");
for (String s : jsonObject.keySet()) {
url.append(s).append("=").append(jsonObject.get(s)).append("&");
}
String substring = url.substring(0, url.length() - 1);
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(new HttpGet(substring));
System.out.println(EntityUtils.toString(closeableHttpResponse.getEntity()));
}
java 接口
@GetMapping("/get/params")
public JSONObject getParams(@RequestParam String id, @RequestParam("name") String userName){}
二、post 请求
1、post 请求传递 x-www-form-urlencoded 参数
请求地址:http://127.0.0.1:8080/HttpClient/post/params/x-www
UrlEncodedFormEntity 继承 StringEntity 构造方法默认 CONTENT_TYPE = "Content-Type: application/x-www-form-urlencoded; charset=UTF-8"
所以传递参数可以在 url 后使用 & 拼接参数
@Test
public void getPost() throws IOException {
String url = "http://127.0.0.1:8080/HttpClient/post/params/x-www";
List<NameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("name", "admin"));
form.add(new BasicNameValuePair("password", "123456"));
HttpEntity reqEntity = new UrlEncodedFormEntity(form, "utf-8");
Header header = new BasicHeader("Connection", "Keep-Alive");
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(reqEntity);
httpPost.setHeader(header);
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36");
// 默认 Content-Type
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;");
httpPost.setConfig(requestConfig);
HttpClient httpClient = HttpClients.custom().build();
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
}
java 接口
@PostMapping("/post/params/x-www")
public JSONObject postParams(String name, String password) {}
2、post/get 请求传递 json 参数
StringEntity 可以传递 json 参数,默认 CONTENT_TYPE = "text/plain; charset=ISO-8859-1“
请求地址:http://127.0.0.1:8080/HttpClient/post/params/json
@Test
public void getPostFormData() throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("account", "admin");
map.put("password", "123456");
JSONObject jsonObject = new JSONObject(map);
String url = "http://127.0.0.1:8080/HttpClient/post/params/json";
StringEntity se = new StringEntity(jsonObject.toJSONString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");//发送json需要设置contentType
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(se);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
log.info(EntityUtils.toString(response.getEntity()));
}
java 接口
@PostMapping("/post/params/json")
public JSONObject postParams(@RequestBody Map<String, Object> map) {}
3、post 请求传递 multipart/form-data 参数(含文件)
传递 multipart/form-data 参数需要导入 httpmime 依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
请求地址:http://127.0.0.1:8080/okhttp3/post/params_from_async
@Test
public void getPostFormFile() throws IOException {
File file = new File("C:\\Users\\Administrator\\Pictures\\小程序\\126.jpg");
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// 文件
multipartEntityBuilder.addBinaryBody("file", file, ContentType.IMAGE_JPEG, "126.jpg");
// 文本
multipartEntityBuilder.addTextBody("name", "admin", ContentType.TEXT_PLAIN);
multipartEntityBuilder.addTextBody("password", "123456", ContentType.TEXT_PLAIN);
HttpEntity httpEntity = multipartEntityBuilder.build();
String url = "http://127.0.0.1:8080/okhttp3/post/params_from_async";
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(httpEntity);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
log.info(EntityUtils.toString(response.getEntity()));
}
java 接口
@PostMapping("/post/params_from_async")
public JSONObject postParamsFromAsync(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws InterruptedException, IOException, ServletException {}
三、关闭 Debug 日志打印
如果你只使用 main 方法调用 Api 接口,控制台会打印很多无用日志(如果是 Springboot 项目可以配置日志配置文件,如:loback.xml),main 方法可以通过调整日志级别关闭 Debug 日志打印
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
main 方法调用控制台打印无用日志
调整日志级别
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.LoggerFactory;
public class TestBlob {
public static void main(String[] args) {
((LoggerContext) LoggerFactory.getILoggerFactory())
.getLoggerList()
.forEach(logger -> logger.setLevel(Level.ERROR));
System.out.println(getArticleCount());
System.out.println(ArrayUtils.toString(getUrl()));
}
}
相关文章
- apache tomcat 闪退[通俗易懂]
- python django 数据库_Apache+Mysql+PHP/Python简单项目
- Apache DolphinScheduler使用学习文档
- 配置Apache把子目录设置为二级站点
- 利用Apache commons exec 实现指定应用打开对应文件详解编程语言
- 利用Apache commons net 包实现简单的POP3邮件详解编程语言
- 服务Linux下重启Apache服务的步骤(linux重启apache)
- Linux 下 Apache 服务器安装指南(linux安装apache)
- Apache 软件基金会的开源社区法则
- 如何正确卸载Linux服务器上的Apache Web服务器?(linux卸载apache)
- 使用Apache和MSSQL构建强大的数据库系统(apache mssql)
- Apache与MySQL的完美融合开启精彩程序之旅(apache加mysql)
- 用Apache反向代理设置对外的WWW和文件服务器
- apache配置开启网站服务步骤
- PHP正确配置mysql(apache环境)
- 阿里云linux服务器下安装Apache的简单方法
- WampServer下安装多个版本的PHP、mysql、apache图文教程