HttpURLConnection發送文件問題

由於工作需要,我需要在後臺servlet模擬post向服務器發送數據,所以我用了HttpURLConnection類來實現,並且發送字符串數據已經能夠實現了,但是不知道發送文件數據該如何實現。
發送數據代碼如下
[code]URL url = new URL(
"http://**********");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","multipart/form-data; boundary=Bounday---");
connection.setRequestProperty("Cache-Control","no-cache");

java.io.OutputStream os=connection.getOutputStream();
OutputStreamWriter osw=new OutputStreamWriter(os);
//BufferedWriter bWriter = new BufferedWriter(osw);
//發送字符串數據
osw.write("字符串數據");
osw.flush();
/*發送文件數據該如何實現*/


// 接收數據
DataInputStream in = new DataInputStream(connection
.getInputStream());
byte[] bytes = new byte[2];
in.read(bytes);
//String result = new String(bytes);


BufferedReader inss = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
StringBuffer content= new StringBuffer();
while((line = inss.readLine()) != null){//line爲返回值,這就可以判斷是否成功、
content.append(line);
}
inss.close() ;
inss=null;
url=null;[/code]
服務器端接收數據代碼如下
[code]BufferedReader bufferdeReader = request.getReader();
StringBuffer sb1 = new StringBuffer();
String tempStr = null;
while ((tempStr = bufferdeReader.readLine()) != null) {
String s = tempStr;
sb1.append(s);
}[/code]
現在我不會的是通過HttpURLConnection發送文件的發送端代碼該如何寫(如要發送的文件爲d:\a.jsp),接收端接收文件的代碼該如何寫。希望各位大哥大姐指教。或者給一個HttpURLConnection這個類的詳細說明文檔也行,網上找的都說得比較簡單。


再問一個問題。

現在文件傳輸的問題解決了,但是現在有個問題是,我在發送文件的時候,如何把文件名稱也發送過去,在那邊如何能夠獲取到文件名稱呢?如果都是流的形式傳輸的,我如何在流中區分出文件名信息和文件流信息??
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章