示例 http客戶端 用的是 okhttp,也可以用 UrlConnetcion或者apache
1、引入Maven
okhttp官網(wǎng)文章來源:http://www.zghlxwxcb.cn/news/detail-657309.html
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.9</version>
</dependency>
也可以下載 okhttp
jar方式引入文章來源地址http://www.zghlxwxcb.cn/news/detail-657309.html
1.1、okhttp發(fā)起請(qǐng)求官網(wǎng)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";
// 創(chuàng)建一個(gè) okhttp客戶端線程池
OkHttpClient client = new OkHttpClient.Builder()
.connectionPool(new ConnectionPool(20, 2, TimeUnit.MINUTES))
.build();
// 構(gòu)建請(qǐng)求對(duì)象
Request request = new Request.Builder().url(url).get().build();
// 發(fā)起請(qǐng)求得到請(qǐng)求結(jié)果
Response response = client.newCall(request).execute();
// 獲取請(qǐng)求結(jié)果
ResponseBody responseBody = response.body();
if (null != responseBody) {
// 獲取文件后綴類型 可以使用 responseBody.contentType() 獲取 ContentType,我這邊知道這個(gè)url文件的類型
String suffix = ".jpeg";
// 創(chuàng)建一個(gè)文件
String filename = "E:\\test\\" + System.currentTimeMillis() + suffix;
File file = new File(filename);
// 判斷目錄是否存在,不存在則創(chuàng)建目錄
File parent = new File(file.getParent());
if(!parent.exists()){
parent.mkdir();
}
// 判斷文件是否存在, 不存在創(chuàng)建文件
if (!file.exists()) {
if (file.createNewFile()) {
// 獲取請(qǐng)求結(jié)果輸入流
InputStream rInputStream = responseBody.byteStream();
// 創(chuàng)建讀取字節(jié)流的byte數(shù)組
byte[] buffer = new byte[500];
int areRead;
// 創(chuàng)建文件輸出流
FileOutputStream outputStream = new FileOutputStream(file );
// 使用輸入流讀取字節(jié),在輸出到文件
while ((areRead = rInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, areRead);
}
rInputStream.close();
outputStream.close();
}
}
}
response.close();
}
}
3、擴(kuò)充,讀寫 txt文件內(nèi)容
3.1讀寫內(nèi)容
/**
* 創(chuàng)建文件以及文件對(duì)應(yīng)的目錄
* @param path 文件路徑,例如 E:\test\測(cè)試.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內(nèi)容
* @param file {@link File}
* @return 字符串
*/
private String readTxt(File file) throws IOException {
StringBuilder sb = new StringBuilder();
// 使用字符流讀取
BufferedReader reader = new BufferedReader(new FileReader(file));
// 讀取每一行的內(nèi)容
String readLine;
while ((readLine = reader.readLine()) != null){
sb.append(readLine);
}
String result = sb.toString();
System.out.printf("讀取內(nèi)容: \n %s", result);
reader.close();
/*
// 使用字節(jié)流讀取
long fileLength = file.length();
// 創(chuàng)建一個(gè)用于讀取指定字節(jié)大小的數(shù)組
byte[] bytes = new byte[(int) fileLength];
// 創(chuàng)建一個(gè)文件輸入流
FileInputStream fileInputStream = new FileInputStream(file);
// 使用 文件輸入流讀取字節(jié)輸入到 字節(jié)數(shù)組中
int areRead = fileInputStream.read(bytes);
String result2 = new String(bytes);
fileInputStream.close();
*/
return result;
}
@Test
public void writeTxt() throws IOException {
String path = "E:\\test2\\測(cè)試.txt";
File file = createFile(path);
// 讀取現(xiàn)在已有的內(nèi)容
String readTxt = readTxt(file);
// 創(chuàng)建一個(gè)文件輸出流
FileOutputStream fileOutputStream = new FileOutputStream(file);
// 之前的內(nèi)容
fileOutputStream.write(readTxt.getBytes(StandardCharsets.UTF_8));
// 換行, 使用Java的自定義換行符號(hào),會(huì)根據(jù)不同系統(tǒng)平臺(tái)轉(zhuǎn)義
String newLine = System.getProperty("line.separator");
fileOutputStream.write(newLine.getBytes());
// 追加的內(nèi)容
fileOutputStream.write((String.valueOf(System.currentTimeMillis()) + " \r\n").getBytes(StandardCharsets.UTF_8));
// 關(guān)閉資源
fileOutputStream.flush();
fileOutputStream.close();
}
到了這里,關(guān)于okhttp下載文件 Java下載文件 javaokhttp下載文件 下載文件 java下載 okhttp下載 okhttp的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!