原理是: 分析文件上傳的數(shù)據(jù)格式,然后根據(jù)格式構造相應的發(fā)送給服務器的字符串。
格式如下:這里的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)表示各個數(shù)據(jù)必須以(\r\n)結尾。
下面按照這些數(shù)據(jù)結構進行請求:
private static final String CONTENT_TYPE = "multipart/form-data"; //內(nèi)容類型
private static final String BOUNDARY = "FlPm4LpSXsE" ; //定義數(shù)據(jù)分隔符(可以隨意更改)
創(chuàng)建HttpsURLConnection 連接
public static HttpsURLConnection getHttpsURLConnectionMul(Context context, String url, String method) {
URL u;
HttpsURLConnection connection = null;
try {
u = new URL(url);
connection = (HttpsURLConnection) u.openConnection();
connection.setRequestMethod(method);//"POST" "GET"
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
// connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Content-Type", "multipart/form-data");
connection.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
connection.setConnectTimeout(10000);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
把數(shù)據(jù)寫入輸出流
DataOutputStream ds = new DataOutputStream(connection.getOutputStream());
addText(your_value1,your_value2,ds);
private void addText(String file_sum,String json_data,OutputStream output) {
String lineStart = "--";
String boundary = "FlPm4LpSXsE"; // 數(shù)據(jù)分隔符
String lineEnd ="\r\n";
StringBuilder sb = new StringBuilder();
sb.append(lineStart + boundary + lineEnd);
sb.append("Content-Disposition: form-data; name=\"your_key1\"" + lineEnd);
sb.append(lineEnd);
sb.append(your_value1+ lineEnd);
sb.append(lineStart + boundary + lineEnd);
sb.append("Content-Disposition: form-data; name=\"your_key2\"" + lineEnd);
sb.append(lineEnd);
sb.append(your_value2+ lineEnd);
String ss = "\r\n--" + boundary + "--\r\n";
sb.append(ss);
try {
Log.e(TAG,"上傳的表單數(shù)據(jù): " + sb.toString());
output.write(sb.toString().getBytes("utf-8"),0,sb.toString().getBytes("utf-8").length);// 發(fā)送表單字段數(shù)據(jù)
output.flush();
output.close();
} catch (IOException e) {
Log.e(TAG,"上傳的表單數(shù)據(jù)寫入異常: " + e.getCause());
throw new RuntimeException(e);
}
}
遇到的坑:
因為我創(chuàng)建 HttpsURLConnection 所定義數(shù)據(jù)分隔符 和寫入DataOutputStream里的所定義的數(shù)據(jù)分隔符不一致,導致服務端接收不到數(shù)據(jù)