日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

java http 上传_Java使用HttpURLConnection上传文件

發(fā)布時間:2025/4/16 java 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java http 上传_Java使用HttpURLConnection上传文件 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

從普通Web頁面上傳文件非常easy。僅僅須要在form標(biāo)簽叫上enctype="multipart/form-data"就可以,剩余工作便都交給瀏覽器去完畢數(shù)據(jù)收集并發(fā)送Http請求。可是假設(shè)沒有頁面的話要怎么上傳文件呢?

因為脫離了瀏覽器的環(huán)境,我們就要自己去完畢數(shù)據(jù)的收集并發(fā)送請求。所以就非常麻煩了。首先我們來寫個JSP頁面并看看瀏覽器發(fā)出的Http請求是什么樣的

JSP頁面:

TestSubmit

參數(shù)

文件1

文件2

假如我參數(shù)寫的內(nèi)容是hello word,然后二個文件是二個簡單的txt文件。form提交的信息為:

-----------------------------7da2e536604c8

Content-Disposition: form-data; name="username"

hello word

-----------------------------7da2e536604c8

Content-Disposition: form-data; name="file1"; filename="D:/haha.txt"

Content-Type: text/plain

haha

hahaha

-----------------------------7da2e536604c8

Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt"

Content-Type: text/plain

messi

huhu

-----------------------------7da2e536604c8--

研究下規(guī)律發(fā)現(xiàn)有例如以下幾點特征:

1. 第一行是“-----------------------------7da2e536604c8”作為分隔符,然后是“/r/n”回車換行符。 這個7da2e536604c8分隔符瀏覽器是隨機生成的。

2. 第二行是Content-Disposition: form-data; name="username"。代表form表單的數(shù)據(jù)域,name相應(yīng)頁面input標(biāo)簽的name值。

3. 第三行是“/r/n”回車換行符。

4. 第四行是參數(shù)username的值。

5. 第五行是7da2e536604c8分隔符。

6. 從第六行到第十行和從第十二行到第十六行,各自是上傳的兩個文件的數(shù)據(jù)域。

7. 第十二行是Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt"。name相應(yīng)頁面input標(biāo)簽的name值。filename相應(yīng)要上傳的文件名稱(包含路徑在內(nèi))。

8. 第十三行假設(shè)是文件就有Content-Type: text/plain。這里上傳的是txt文件所以是text/plain。假設(shè)上穿的是jpg圖片的話就是image/jpg了,能夠自己試試看看。

然后就是回車換行符。

9. 第十五、十六行就是文件的內(nèi)容了。如:

messi

huhu

10. 最后一行是-----------------------------7da2e536604c8--。注意最后多了二個“--”。作為結(jié)束的標(biāo)志。

那么我們僅僅要模擬這個數(shù)據(jù),并寫入到Http請求中便能實現(xiàn)文件的上傳。

事實上。在我之前的文章:HttpClient使用具體解釋?,就已經(jīng)有利用HttpClient工具包上傳文件的樣例。HttpClient是Apache的一個強大的模擬并發(fā)送全部Http請求的開源類庫,有時間的。大家能夠?qū)W習(xí)學(xué)習(xí),但本篇文章中。并不以HttpClient為例。而是採用Java自帶的HttpURLConnection實現(xiàn)的。

import java.io.BufferedReader;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import net.sf.jmimemagic.Magic;

import net.sf.jmimemagic.MagicMatch;

public class HttpPostUploadUtil {

/**

* @param args

*/

public static void main(String[] args) {

String filepath = "E:\\ziliao\\0.jpg";

String urlStr = "http://127.0.0.1:8080/minicms/up/up_result.jsp";

Map textMap = new HashMap();

textMap.put("name", "testname");

Map fileMap = new HashMap();

fileMap.put("userfile", filepath);

String ret = formUpload(urlStr, textMap, fileMap);

System.out.println(ret);

}

/**

* 上傳圖片

* @param urlStr

* @param textMap

* @param fileMap

* @return

*/

public static String formUpload(String urlStr, Map textMap, Map fileMap) {

String res = "";

HttpURLConnection conn = null;

String BOUNDARY = "---------------------------123821742118716"; //boundary就是request頭和上傳文件內(nèi)容的分隔符

try {

URL url = new URL(urlStr);

conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5000);

conn.setReadTimeout(30000);

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setUseCaches(false);

conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");

conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

OutputStream out = new DataOutputStream(conn.getOutputStream());

// text

if (textMap != null) {

StringBuffer strBuf = new StringBuffer();

Iterator> iter = textMap.entrySet().iterator();

while (iter.hasNext()) {

Map.Entry entry = iter.next();

String inputName = (String) entry.getKey();

String inputValue = (String) entry.getValue();

if (inputValue == null) {

continue;

}

strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");

strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");

strBuf.append(inputValue);

}

out.write(strBuf.toString().getBytes());

}

// file

if (fileMap != null) {

Iterator> iter = fileMap.entrySet().iterator();

while (iter.hasNext()) {

Map.Entry entry = iter.next();

String inputName = (String) entry.getKey();

String inputValue = (String) entry.getValue();

if (inputValue == null) {

continue;

}

File file = new File(inputValue);

String filename = file.getName();

MagicMatch match = Magic.getMagicMatch(file, false, true);

String contentType = match.getMimeType();

StringBuffer strBuf = new StringBuffer();

strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");

strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");

strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

out.write(strBuf.toString().getBytes());

DataInputStream in = new DataInputStream(new FileInputStream(file));

int bytes = 0;

byte[] bufferOut = new byte[1024];

while ((bytes = in.read(bufferOut)) != -1) {

out.write(bufferOut, 0, bytes);

}

in.close();

}

}

byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();

out.write(endData);

out.flush();

out.close();

// 讀取返回數(shù)據(jù)

StringBuffer strBuf = new StringBuffer();

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String line = null;

while ((line = reader.readLine()) != null) {

strBuf.append(line).append("\n");

}

res = strBuf.toString();

reader.close();

reader = null;

} catch (Exception e) {

System.out.println("發(fā)送POST請求出錯。" + urlStr);

e.printStackTrace();

} finally {

if (conn != null) {

conn.disconnect();

conn = null;

}

}

return res;

}

}

在上述代碼中,關(guān)于contentType的獲取方式。我在上篇文章中已經(jīng)講述過了,有興趣的能夠看看。

總結(jié)

以上是生活随笔為你收集整理的java http 上传_Java使用HttpURLConnection上传文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。