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这个类的详细说明文档也行,网上找的都说得比较简单。


再问一个问题。

现在文件传输的问题解决了,但是现在有个问题是,我在发送文件的时候,如何把文件名称也发送过去,在那边如何能够获取到文件名称呢?如果都是流的形式传输的,我如何在流中区分出文件名信息和文件流信息??
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章