private void upLoadFile(String filePath, HashMap<String, String> paramsMap) {
try {
String baseUrl = "https://baidu.com/uploadFile";
File file = new File(filePath);
URL url = new URL(baseUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
urlConn.setConnectTimeout(5 * 1000);
urlConn.setReadTimeout(5 * 1000);
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("connection", "Keep-Alive");
urlConn.setRequestProperty("Accept-Charset", "UTF-8");
urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****");
String name = file.getName();
DataOutputStream requestStream = new DataOutputStream(urlConn.getOutputStream());
requestStream.writeBytes("--" + "*****" + "\r\n");
StringBuilder tempParams = new StringBuilder();
tempParams.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + name + "\"; ");
int pos = 0;
int size = paramsMap.size();
for (String key : paramsMap.keySet()) {
tempParams.append( String.format("%s=\"%s\"", key, paramsMap.get(key), "utf-8"));
if (pos < size-1) {
tempParams.append("; ");
}
pos++;
}
tempParams.append("\r\n");
tempParams.append("Content-Type: application/octet-stream\r\n");
tempParams.append("\r\n");
String params = tempParams.toString();
requestStream.writeBytes(params);
FileInputStream fileInput = new FileInputStream(file);
int bytesRead;
byte[] buffer = new byte[1024];
DataInputStream in = new DataInputStream(new FileInputStream(file));
while ((bytesRead = in.read(buffer)) != -1) {
requestStream.write(buffer, 0, bytesRead);
}
requestStream.writeBytes("\r\n");
requestStream.flush();
requestStream.writeBytes("--" + "*****" + "--" + "\r\n");
requestStream.flush();
fileInput.close();
int statusCode = urlConn.getResponseCode();
if (statusCode == 200) {
String result = streamToString(urlConn.getInputStream());
Log.e(TAG, "上传成功,result--->" + result);
} else {
Log.e(TAG, "上传失败");
}
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}