Android中实现带参上传文件的http请求工具!
在Android中我们经常会碰到一些特殊接口, 在带参数的情况,同时上传文件. 我们写一个工具,在以后的项目中基本上都能用到.
代码实现如下:
public String httpFileUpload(String url, Map<String, String> params, File file, String fileName) throws IOException {
HttpURLConnection urlConnection = null;
String fileDelimiter = "********";
String endString = "\r\n";
String prefix = "--";
try {
String content = "";
for (Entry<String, String> entry : params.entrySet()) {
content += entry.getKey() + "=" + entry.getValue() + "&";
}
content = content.substring(0, content.length() - 1);
url += "&" + content;
URL temp = new URL(url.replaceAll(" ", "%20"));
urlConnection = (HttpURLConnection) temp.openConnection();
urlConnection.setConnectTimeout(connectionTimeout);
urlConnection.setReadTimeout(soTimeout);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + fileDelimiter);
OutputStream out = new DataOutputStream(urlConnection.getOutputStream());
StringBuffer strBuf = new StringBuffer();
strBuf.append(prefix + fileDelimiter + endString);
strBuf.append("Content-Disposition: form-data; name=\"logFile\"; filename=\"" + fileName + "\"" + endString);
strBuf.append("Content-Type: text/plain" + endString + endString);
out.write(strBuf.toString().getBytes("UTF-8"));
if (file != null) {
FileInputStream input = new FileInputStream(file);
byte[] bufferOut = new byte[1024];
int bytes;
while ((bytes = input.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
input.close();
}
out.write((endString + prefix + fileDelimiter + prefix + endString).getBytes("UTF-8"));
InputStream inputStream = urlConnection.getInputStream();
String result = getResponseAsString(inputStream, urlConnection.getContentType());
return result;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
httpFileUpload方法中的url为接口地址,params为请求参数,file为文件,fileName为文件名
本文介绍了一个用于Android项目的实用工具,该工具能够实现带参数的同时上传文件功能,适用于各种需要文件上传的应用场景。
1575

被折叠的 条评论
为什么被折叠?



