在使用HttpURLConnection作为请求方式,有时候会有这样的需求。给一个接口上传文件,并且同时要提交其他的参数。但你可能会遇到这样的问题,就是无法同时上传文件的时候又提交其他类型的参数。怎么解决这个问题呢?
注释比较清晰,直接看代码吧:
private static HttpURLConnection uRLConnection;
private static final String CHARSET = "UTF-8";
/**
* 文件上传
*
* @author:gj
* @date: 2017/6/8
* @time: 11:25
* urlAddress 路径
* file 要上传的文件、
* fileKey 服务器端接收文件的字段
* param 需要同时提交的参数
* newFileName 给上传的文件重新命名,null则用文件原名
**/
public static String uploadFile(String urlAddress, File file,
String fileKey, Map<String, String> param, String newFileName) {
Log.i(TAG, "文件上传");
String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型
String response = "";//服务器端返回值
try {
URL url = new URL(urlAddress);
uRLConnection = (HttpURLConnection) url.openConnection();//打开连接
uRLConnection.setDoInput(true);//以后就可以使用conn.getOutputStream().read()
uRLConnection.setDoOutput(true);//设置以后就可以使用conn.getOutputStream().write()
uRLConnection.setRequestMethod("POST");//使用post提交
uRLConnection.setUseCaches(false);//不使用缓存
uRLConnection.setInstanceFollowRedirects(false);//不自动重定向
uRLConnection.setRequestProperty("Content-Type", CONTENT_TYPE
+ ";boundary=" + BOUNDARY);//设置请求头
uRLConnection.setRequestProperty("connection", "keep-alive");//保持连接
uRLConnection.setRequestProperty("Charset", CHARSET);
uRLConnection.setConnectTimeout(10000);//请求超时时间
//开始请求连接
uRLConnection.connect();
//获取输出流
DataOutputStream out = new DataOutputStream(
uRLConnection.getOutputStream());
/***
* 以下先是用于上传参数
*/
if (param != null && param.size() > 0) {
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
StringBuffer sb = new StringBuffer();
String key = it.next();
String value = param.get(key);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"")
.append(key).append("\"").append(LINE_END)
.append(LINE_END);
sb.append(value).append(LINE_END);
String params = sb.toString();
Log.i(TAG, key + "=" + params + "##");
out.write(params.getBytes());
// dos.flush();
}
}
//参数上传完开始上传文件
if (file != null) {
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名
*/
if (null != newFileName && "" != newFileName) {
sb.append("Content-Disposition: form-data; name=\"" + fileKey
+ "\"; filename=\"" + newFileName + "\"" + LINE_END);
} else {
sb.append("Content-Disposition: form-data; name=\"" + fileKey
+ "\"; filename=\"" + file.getName() + "\"" + LINE_END);
}
sb.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINE_END);
sb.append(LINE_END);
out.write(sb.toString().getBytes());
InputStream isinput = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = isinput.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
out.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
out.write(end_data);
isinput.close();
out.flush();
}
int i = uRLConnection.getResponseCode();
Log.i("i", i + "");
if (i == 200) {
InputStream is = uRLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
while ((readLine = br.readLine()) != null) {
// response = br.readLine();
response = readLine;
}
is.close();
br.close();
} else {
response = uRLConnection.getResponseCode() + "";
}
//关闭连接
uRLConnection.disconnect();
} catch (Exception e) {
return e.getMessage();
}
Log.i(TAG, "到服务器拿response" + response);
return response;
}