okhttp下载文件 Java下载文件 javaokhttp下载文件 下载文件 java下载 okhttp下载 okhttp

okhttp下载文件 Java下载文件 javaokhttp下载文件 下载文件 java下载 okhttp下载 okhttp

示例 http客户端 用的是 okhttp,也可以用 UrlConnetcion或者apache

1、引入Maven

okhttp官网

java 复制代码
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.14.9</version>
</dependency>

也可以下载 okhttp jar方式引入

1.1、okhttp发起请求官网Demo

java 复制代码
public static final MediaType JSON = MediaType.get("application/json");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(json, JSON);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

2、下载文件

java 复制代码
public class TestDownload {

    public static void main(String args[]) {
       // 图片文件地址
        String url = "https://himg.bdimg.com/sys/portraitn/item/public.1.c9145b32.BtcNjpu-t6NEqWtWFh3ICg";
        
        // 创建一个 okhttp客户端线程池
        OkHttpClient client = new OkHttpClient.Builder()
                .connectionPool(new ConnectionPool(20, 2, TimeUnit.MINUTES))
                .build();
        
        // 构建请求对象
        Request request = new Request.Builder().url(url).get().build();
        
        // 发起请求得到请求结果
        Response response = client.newCall(request).execute();
        
        // 获取请求结果
        ResponseBody responseBody = response.body();
        if (null != responseBody) {
            // 获取文件后缀类型 可以使用 responseBody.contentType() 获取 ContentType,我这边知道这个url文件的类型
            String suffix = ".jpeg";
            
            // 创建一个文件
            String filename = "E:\\test\\" + System.currentTimeMillis() + suffix;
            
            File file = new File(filename);
    
            // 判断目录是否存在,不存在则创建目录
    
            File parent = new File(file.getParent());
            if(!parent.exists()){
                parent.mkdir();
            }
            
            // 判断文件是否存在, 不存在创建文件
            if (!file.exists()) {
                if (file.createNewFile()) {
                    // 获取请求结果输入流
                    InputStream rInputStream = responseBody.byteStream();
                    
                    // 创建读取字节流的byte数组
                    byte[] buffer = new byte[500];
                    
                    int areRead;
                    
                    // 创建文件输出流
                    FileOutputStream outputStream = new FileOutputStream(file );
                    
                    // 使用输入流读取字节,在输出到文件
                    while ((areRead = rInputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, areRead);
                    }
                    rInputStream.close();
                    outputStream.close();
                }
            }
        }
        response.close();
    }
}

3、扩充,读写 txt文件内容

3.1读写内容

java 复制代码
    /**
     * 创建文件以及文件对应的目录
     * @param path 文件路径,例如 E:\test\测试.txt
     * @return {@link File}
     */
    private File createFile(String path) throws IOException {
        File file = new File(path);
        
        // 判断目录是否存在
        File parent = new File(file.getParent());
        if(!parent.exists()){
            parent.mkdir();
        }
        
        if(!file.exists()){
            file.createNewFile();
        }
        return file;
    }
    
    /**
     * 读取txt内容
     * @param file {@link File}
     * @return 字符串
     */
    private String readTxt(File file) throws IOException {
        
        StringBuilder sb = new StringBuilder();
        
        // 使用字符流读取
        BufferedReader reader = new BufferedReader(new FileReader(file));
        
        // 读取每一行的内容
        String readLine;
        
        while ((readLine = reader.readLine()) != null){
            sb.append(readLine);
        }
    
        String result = sb.toString();
        
        System.out.printf("读取内容: \n %s", result);
        
        reader.close();
        
        /*
        // 使用字节流读取
        long fileLength = file.length();
        
        // 创建一个用于读取指定字节大小的数组
        byte[] bytes = new byte[(int) fileLength];
        
        // 创建一个文件输入流
        FileInputStream fileInputStream = new FileInputStream(file);
        
        // 使用 文件输入流读取字节输入到 字节数组中
        int areRead = fileInputStream.read(bytes);
        
        String result2 = new String(bytes);

        fileInputStream.close();
   
         */
        return result;
    }
    
    @Test
    public void writeTxt() throws IOException {
        String path = "E:\\test2\\测试.txt";
        
        File file = createFile(path);
        
        // 读取现在已有的内容
        String readTxt = readTxt(file);
        
        // 创建一个文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        
        // 之前的内容
        fileOutputStream.write(readTxt.getBytes(StandardCharsets.UTF_8));
    
        // 换行, 使用Java的自定义换行符号,会根据不同系统平台转义
        String newLine = System.getProperty("line.separator");
        fileOutputStream.write(newLine.getBytes());
        
        // 追加的内容
        fileOutputStream.write((String.valueOf(System.currentTimeMillis()) + " \r\n").getBytes(StandardCharsets.UTF_8));
        
        // 关闭资源
        fileOutputStream.flush();
        fileOutputStream.close();
    }
相关推荐
豆本-豆豆奶18 分钟前
23个Python在自然语言处理中的应用实例
开发语言·python·自然语言处理·编程语音
曳渔24 分钟前
Java-数据结构-二叉树-习题(三)  ̄へ ̄
java·开发语言·数据结构·算法·链表
shark-chili34 分钟前
数据结构与算法-Trie树添加与搜索
java·数据结构·算法·leetcode
白乐天_n36 分钟前
FRIDA-JSAPI:Java使用
java·jsapi·frida
你可以自己看40 分钟前
python中函数式编程与高阶函数,装饰器与生成器,异常处理与日志记录以及项目实战
服务器·开发语言·python
无奇不有 不置可否1 小时前
JVM基础篇学习笔记
java·jvm
gopher95111 小时前
go语言 数组和切片
开发语言·golang
ymchuangke1 小时前
线性规划------ + 案例 + Python源码求解(见文中)
开发语言·python
gopher95111 小时前
go语言Map详解
开发语言·golang
Python私教1 小时前
Go语言现代web开发15 Mutex 互斥锁
开发语言·前端·golang