public String post(String url, HashMap param, List files, String fileName) {
String result = "";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "ABCDEFG";
try {
URL requestUrl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
httpURLConnection.setChunkedStreamingMode(128 * 1024);//128k防止内存过高
//允许输入输出流
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
//字段
Iterator iterator = param.entrySet().iterator();
while (iterator.hasNext()) {
dos.writeBytes(twoHyphens + boundary + end);
Map.Entry entry = (Map.Entry) iterator.next();
dos.writeBytes("Content-Disposition:form-data;name=\"" + entry.getKey() + "\"" + end);
dos.writeBytes(end);
dos.writeBytes(URLEncoder.encode(entry.getValue().toString(),"UTF-8"));
dos.writeBytes(end);
}
//文件
for (File file : files) {
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition:form-data;name=\"" + fileName + "\";filename=\"" + file.getName() + "\"" + end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[8 * 1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
}
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(isr);
result = br.readLine();
dos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Android", e.getLocalizedMessage());
}
return result;
}
public String post(String url, HashMap param, List files, String fileName) {}
url:请求地址
param:请求参数
files:要传送的文件
fileName:接受文件要用的名字
自己撸的服务端是PHP的
感觉自己撸的传输速度还是比较快的