commons-io与HttpClient

44 阅读1分钟

Commons-io

commons.apache.org/proper/comm…

前提前要一定对原生的IO流有一定的知识储备


<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.21.0</version>
</dependency>

QQ20260128-165252.png

这些是官方提供的主要核心方法(IDEA 进入方法右击show diagram,选择方法),而且很多方法非常见名知意。

  • IOUtils(基础)

由于个人经历,无法再次重新构建底层的知识库。IOutil其实对inputStream,outputStream,read,witer这四个进行了二次改进。

  • FileUtils(重要)

这个很简单,文件的的相关操作,比如删除,创建,输出等等。

  • FilenameUtils(重要)

文件名称的获取

  • FileSystemUtils(重要)

系统文件的操作,当然也要注意windows与linux的系统文件,最重要的是磁盘操作。

  • EdianUtils

(个人感觉不常用)字节序转换操作

首先官方提供的这些方法并不只有这些,还有很多,只是选取第一个包,commons.io

QQ20260128-173003.png

操作方式和jdk8官方文档一样

docs.oracle.com/javase/8/do…

其实最主要的是下面这段代码(需要掌握URL对象)

  • 获取文件后缀名(需要分析是否需要)
FilenameUtils.getExtension(URL地址)
  • 输出文件(记得用UUID作为文件名称)
FileUtils.copyURLToFile(URL地址,文件输出文件夹);

httpclient

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
    <scope>compile</scope>
</dependency>
  • get请求
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(URL地址);
CloseableHttpResponse response = httpClient.execute(httpGet);
String result = EntityUtils.toString( response.getEntity());
  • post请求
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url地址);

StringEntity entity = new StringEntity(JSON对象, ContentType.APPLICATION_JSON);
post.setEntity(entity);

CloseableHttpResponse response = httpClient.execute(post);
EntityUtils.toString(response.getEntity());

等有时间单独出一期关于httpclient的语法

下一期,javax.websocket与jackson