用java的.net包和http的post实现upload和download- -
用java的.net包和http的post实现upload和download。需要用到的对象有URL, HttpURLConnection, OutputStreamWriter等.下面给出源码:
1.文件上传:
HttpURLConnection conn = null;
BufferedWriter bWriter = null;
OutputStream os = null;
OutputStreamWriter osw = null;
String strData = "filename=postest.txt&data=1234566778888";
try {
URL url1 = new URL("http://yoururl/upload.php");
conn = (HttpURLConnection)url1.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setUseCaches( false);
conn.setDoOutput(true);
osw = new OutputStreamWriter(conn.getOutputStream());
osw.write("filename=postest.txt&data=1234567890");
osw.flush() ;
osw.close() ;
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
System.out.println( "connect failed!");
}
catch (Exception e) {
e.printStackTrace(System.out);
}
finally
{
if (osw != null)
try {
osw.close() ;
} catch (IOException e1) {
e1.printStackTrace(System.out);
}
if (conn != null)
conn.disconnect() ;
}
php根据上传数据写文件的代码(一些额外的代码都被去掉了):
if($data!="")
{
$path="filepath/".trim($filename);
$fp = fopen($path,"a");
if($fp)
{
flock($fp,2);
$fw=fputs($fp,$data);
fclose($fp);
Header("Location: http://yourhost/succes.php");
}
else
{
Header("Location: http://yourhost/error.php");
}
}
else
{
Header("Location: http://yourhost/error.php");
}
|
2.文件下载:
HttpURLConnection conn = null;
RandomAccessFile f=null;
InputStream is = null;
int contentlength = 0;
int spos = 0;
int epos = 0;
int nread = 0;
try
{
URL url1 = new URL("yoururl/download.rar");
conn = (HttpURLConnection)url1.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "NetFox");
conn.setRequestProperty("Connection", "Keep-Alive");
for (int i=1;; i++)
{
String head = conn.getHeaderFieldKey(i);
if (head == null)
break;
System.out.println(head+": "+ conn.getHeaderField(head));
}
epos = contentlength = conn.getContentLength() ;
is = conn.getInputStream();
int unitsize = contentlength<1024?contentlength:1024;
byte[] b = new byte[unitsize];
f = new RandomAccessFile("C:/eclipse/workspace/pgtest/download/posttest.rar", "rw");
System.out.println("Receive data beginning:");
while ((nread=is.read(b, 0, unitsize))>0 && spos小于epos)
{
f.write(b);
spos += unitsize;
System.out.println("has received bytes:" + spos);
}
}
catch (FileNotFoundException fnfe)
{
System.out.println("file " + f.toString() + " is not found.");
} catch (Exception e) {
e.printStackTrace(System.out);
}
finally
{
if (f != null)
try {
f.close() ;
} catch (IOException e1) {
e1.printStackTrace(System.out);
}
if (is != null)
try {
is.close();
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
if (conn != null)
conn.disconnect() ;
}
System.out.println("download success!");
|
From:
http://jimjava.bokee.com/414949.html