Android中实现带参上传文件的http请求工具!(表单格式)

本文介绍了一个用于Android项目的实用工具,该工具能够实现带参数的同时上传文件功能,适用于各种需要文件上传的应用场景。

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为文件名

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值