android用HTTP post上傳文件到OSS

最近有一個需求是要上傳音頻信息到服務(wù)器,為了減少自有服務(wù)器的流量,決定使用授權(quán)回調(diào)上傳的形式由客戶端直接上傳到阿里云oss服務(wù)器。
官方文檔
https://help.aliyun.com/document_detail/93939.html?spm=a2c4g.11186623.6.1226.6cd07d2dnW4Ekp
中只給出了使用SDK上傳的方式,并沒有如何自主構(gòu)建post請求,通過sts服務(wù)器拿到的callback信息直接上傳。遂從源碼中找到請求構(gòu)建部分,自行構(gòu)建上傳。

java請求構(gòu)建源碼地址:
https://github.com/aliyun/aliyun-oss-java-sdk/blob/master/src/samples/PostObjectSample.java
簽名URL服務(wù)器返回信息:

image.png

下面給出基于源碼的修改版代碼

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

import java.util.Iterator;
import java.util.Map.Entry;

import javax.activation.MimetypesFileTypeMap;

/**
 * Created by shengtao
 * on 2020/6/1
 */


/**
 * This sample demonstrates how to post object under specfied bucket from Aliyun
 * OSS using the OSS SDK for Java.
 */


public class PostObjectSample {

    // The local file path to upload.
    private static String localFilePath;

    public static void postObject(OssInfoBean bean) throws Exception {
        String urlStr = bean.getRst().getHost();

        // form fields
        Map<String, String> formFields = new LinkedHashMap<String, String>();

        // key
        formFields.put("key", bean.getRst().getKey());
        // Content-Disposition
        localFilePath = Constant.FileNamePath + bean.getRst().getName();
        formFields.put("Content-Disposition", "attachment;filename="
                + localFilePath);
        formFields.put("OSSAccessKeyId", bean.getRst().getOSSAccessKeyId());
        formFields.put("policy", bean.getRst().getPolicy());
        formFields.put("Signature", bean.getRst().getSignature());
        formFields.put("callback", bean.getRst().getCallback());
        formFields.put("filename", bean.getRst().getName());

        String ret = formUpload(urlStr, formFields, localFilePath);

        File f = new File(localFilePath);
        f.delete();
        System.out.println("post reponse formUpload :" + ret);
    }

    private static String formUpload(String urlStr, Map<String, String> formFields, String localFile)
            throws Exception {
        String res = "";
        HttpURLConnection conn = null;
        String boundary = "9431149156168";

        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);
            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // text
            if (formFields != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator<Entry<String, String>> iter = formFields.entrySet().iterator();
                int i = 0;

                while (iter.hasNext()) {
                    Entry<String, String> entry = iter.next();
                    String inputName = entry.getKey();
                    String inputValue = entry.getValue();

                    if (inputValue == null) {
                        continue;
                    }

                    if (i == 0) {
                        strBuf.append("--").append(boundary).append("\r\n");
                        strBuf.append("Content-Disposition: form-data; name=\""
                                + inputName + "\"\r\n\r\n");
                        strBuf.append(inputValue);
                    } else {
                        strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
                        strBuf.append("Content-Disposition: form-data; name=\""
                                + inputName + "\"\r\n\r\n");
                        strBuf.append(inputValue);
                    }

                    i++;
                }
                out.write(strBuf.toString().getBytes());
            }

            // file
            File file = new File(localFile);
            String filename = file.getName();
            String contentType = new MimetypesFileTypeMap().getContentType(file);
            if (contentType == null || contentType.equals("")) {
                contentType = "application/octet-stream";
            }

            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\r\n").append("--").append(boundary)
                    .append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"file\"; "
                    + "filename=\"" + filename + "\"\r\n");
            strBuf.append("Content-Type: " + contentType + "\r\n\r\n");

            out.write(strBuf.toString().getBytes());


            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[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();


            // Gets the file data
            strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.err.println("Send post request exception: " + e);
            throw e;
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }

        return res;
    }
}

使用方法:

                                    PostObjectSample.postObject(body);//body為上面截圖中的內(nèi)容

文件地址為:

Constant.FileNamePath + bean.getRst().getName()//自行修改

上傳成功后 ,ret信息為:

System.out: post reponse formUpload :{"status": 0, "rst": {"md5sum": "d1f2cedc83c***97116c80e53cf"}, "message": "success", "test_flag": 0, "request_no": "7d****f4-85a6-41ea-9285-9fae58901531"}

至此上傳成功。

以上 by:Miyok

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容