public static JSONObject uploadPermanentMediaFile(String requestUrl, File file, String type) {
StringBuffer buffer = new StringBuffer();
JSONObject jsonObject = null;
try {
String boundary = "*****"; // 用于拼接 可自定义
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(20000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(boundary);
sb.append("\r\n");
/***********************************/
sb.append("Content-Disposition: form-data;name=\"type\" \r\n\r\n");
sb.append(type);
sb.append("\r\n--").append(boundary).append("\r\n");
if ("video".equals(type)) {
sb.append("Content-Disposition: form-data;name=\"description\" \r\n\r\n");
sb.append("{\"title\":\"hello title\",\"introduction\":\"hello introduction\"}");
sb.append("\r\n--").append(boundary).append("\r\n");
}
/***********************************/
String filename = file.getName();
sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + filename + "\" \r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
System.out.println(sb.toString());
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + boundary + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}