HttpURLConnection conn = null;
DataOutputStream outStream = null;
try{
String BOUNDARY = "---------------------------7da2137580612"; //資料分界線
String MULTIPART_FORM_DATA ="multipart/form-data";
URL url = new URL(Const.URL);
//上傳表單的檔案
StringBuilder emailSB = new StringBuilder();
emailSB.append("--");
emailSB.append(BOUNDARY);
emailSB.append("\r\n");
emailSB.append("Content-Disposition:form-data;name=\"email\"\r\n\r\n");
emailSB.append(email);
emailSB.append("\r\n");
StringBuilder bitmapSB = new StringBuilder();
bitmapSB.append("--");
bitmapSB.append(BOUNDARY);
bitmapSB.append("\r\n");
bitmapSB.append("Content-Disposition:form-data;name=\"image\";filename=\"image\"\r\n");
bitmapSB.append("Content-Type:image/png\r\n\r\n");
byte[] end_data =("--"+BOUNDARY+"--\r\n").getBytes();//資料結束標誌
File file = new File("/mnt/sdcard/111.png");
FileInputStream fileIS = new FileInputStream(file);
long contentLenght = emailSB.toString().getBytes().length + end_data.length
+ bitmapSB.toString().getBytes().length + file.length() + "\r\n".getBytes().length;
conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true); //允許輸入
conn.setDoOutput(true); //允許輸出
conn.setUseCaches(false); //不使用caches
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("Content-Type",MULTIPART_FORM_DATA+";boundary="+BOUNDARY);
conn.setRequestProperty("Content-Length",Long.toString(contentLenght));
outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(emailSB.toString().getBytes());
outStream.write(bitmapSB.toString().getBytes());
byte[] buffer = new byte[1024];
int len = 0;
while((len = fileIS.read(buffer)) != -1){
outStream.write(buffer, 0, len);
}
outStream.write("\r\n".getBytes());
outStream.write(end_data);
outStream.flush();
int cah = conn.getResponseCode();
if(cah!=200){
System.out.println("上傳失敗");
return;
}
InputStream is = conn.getInputStream();
int ch;
StringBuilder result = new StringBuilder();
while((ch=is.read())!=-1){
result.append((char)ch);
}
System.out.println("result :" + result.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if(outStream != null){
outStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(conn != null){
conn.disconnect();
conn = null;
}
}
使用HttpUrlConnection類比post表單進行檔案上傳平時很少使用,比較麻煩。
原理是: 分析檔案上傳的資料格式,然後根據格式構造相應的發送給伺服器的字串。
格式如下:這裡的httppost123是我自己構造的字串,可以是其他任何的字串
----------httppost123 (\r\n)
Content-Disposition: form-data; name="img"; filename="t.txt" (\r\n)
Content-Type: application/octet-stream (\r\n)
(\r\n)
sdfsdfsdfsdfsdf (\r\n)
----------httppost123 (\r\n)
Content-Disposition: form-data; name="text" (\r\n)
(\r\n)
text tttt (\r\n)
----------httppost123-- (\r\n)
(\r\n)
上面的(\r\n)表示各個資料必須以(\r\n)結尾。