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)结尾。