本文主要是介绍Android中实现带参上传文件的http请求工具!(表单格式),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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中实现带参上传文件的http请求工具!(表单格式)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!