okhttp下载文件 Java下载文件 javaokhttp下载文件 下载文件 java下载 okhttp下载 okhttp
- 1、引入Maven
- 1.1、okhttp发起请求官网Demo
- 2、下载文件
- 3、扩充,读写 txt文件内容
- 3.1读写内容
示例 http客户端 用的是 okhttp,也可以用 UrlConnetcion或者apache
1、引入Maven
okhttp官网
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>3.14.9</version>
</dependency>
也可以下载 okhttp
jar方式引入
1.1、okhttp发起请求官网Demo
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、下载文件
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读写内容
/*** 创建文件以及文件对应的目录* @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;}@Testpublic 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();}