java 文件传输_Java开发之如何通过HTTP方式传输文件
平時我們傳文件,一般都是通過FTP方式,這是最常用的。偶爾也會用到利用共享目錄方式傳文件,在我以前的文章中有提供如何借助共享目錄傳文件。今天我們要說的是通過HTTP方式傳文件,首先在接收方需要有一個接收的接口類,用以在觸發上傳文件后接收文件。下面我們給出HTTP上傳類的實例代碼
public static int upload(String strURL, File[] allFile) {
int status = 200;
for (int i = 0; i < allFile.length; ++i) {
String localFile = allFile[i].getAbsolutePath();
if (!(allFile[i].exists())) {
continue;
}
long startPos = 0L;
HttpClient headclient = new DefaultHttpClient();
HttpHead httphead = new HttpHead(strURL);
try {
httphead.addHeader("Content-Type", "application/octet-stream");
} catch (Exception e) {
e.printStackTrace();
} finally {
headclient.getConnectionManager().shutdown();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(strURL).openConnection();
RandomAccessFile fis = new RandomAccessFile(new File(localFile), "r");
if (startPos < fis.length()) {
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("File-Name", allFile[i].getName());
OutputStream os = conn.getOutputStream();
int rn = 0;
byte[] buf = new byte[4096];
while ((rn = fis.read(buf, 0, 4096)) > 0) {
os.write(buf, 0, rn);
}
os.close();
status = conn.getResponseCode();
}
fis.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
try {
conn.getResponseCode();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
return status;
}
親測,可以直接能用的java上傳類(HTTP方式)。HTTP上傳對于一些小文件是可以,對于一些大文件,因這種協議容易中斷,因此必須考慮斷點續傳,這里我們沒有把斷點續傳考慮進去,不然就太復雜了。
總結
以上是生活随笔為你收集整理的java 文件传输_Java开发之如何通过HTTP方式传输文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 输入三角形的三条边长,求面积
- 下一篇: Java 位运算详解