* 模拟POST Form 方式上传文件到服务器
* @param file 需要上传的文件
* @param uploadUrl 文件上传地址
* @return 返回响应的内容
*/
private String uploadFile(File file, String uploadUrl) {
String BOUNDARY = UUID.randomUUID().toString();
String PREFIX = "--";
String LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data";
HttpURLConnection conn = null;
BufferedReader br = null;
try {
URL url = new URL(uploadUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIME_OUT);
conn.setConnectTimeout(CONNECT_TIME_OUT);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod(HttpPost.METHOD_NAME);
conn.setRequestProperty("Charset", CHARSET);
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
conn.setRequestProperty("Content-Length", String.valueOf(file.length()));
if (file != null && file.exists()) {
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"userfile\"; filename=\"" + file.getName() + "\""
+ LINE_END);
sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[8 * 1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
int responseCode = conn.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
LogUtil.d(TAG, "request success");
br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} else {
LogUtil.d(TAG, "response error");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (conn != null) {
conn.disconnect();
}
}
return null;
}