Android使用multipart/form-dataPOST方式时出现400错误
创始人
2024-10-10 14:00:55
0

其中的错误原因可能是编码问题。以下示例代码演示了如何将文件上传到服务器,并使用multipart/form-data进行POST:

private void uploadFile(String filePath, String uploadUrl) {
    try {
        // 创建文件
        File file = new File(filePath);
        // 设置请求路径
        URL url = new URL(uploadUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置请求方式
        conn.setRequestMethod("POST");
        // 设置请求头
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        // 设置字符集
        conn.setRequestProperty("Charset", "UTF-8");
        // 设置请求超时时间
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);
        // 获取输出流
        OutputStream outStream = conn.getOutputStream();
        // 设置上传参数
        StringBuilder sb = new StringBuilder();
        sb.append("--").append(BOUNDARY).append("\r\n");
        sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type: application/octet-stream\r\n\r\n");
        outStream.write(sb.toString().getBytes());
        // 读取文件数据
        InputStream inStream = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        outStream.write("\r\n".getBytes());
        // 结束标志
        byte[] endData = ("--" + BOUNDARY + "--\r\n").getBytes();
        outStream.write(endData);
        outStream.flush();
        // 获取服务器返回信息
        int res = conn.getResponseCode();
        if (res == 200) {
            InputStream inputStream = conn.getInputStream();
            String result = streamToString(inputStream);
            Log.i(TAG, "uploadFile result: " + result);
        }
        outStream.close();
        conn.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//

相关内容

热门资讯

推荐攻略!微扑克辅助,we p... 推荐攻略!微扑克辅助,we poker免费辅助器,好像是真的有挂(竟然有挂)亲,关键说明,透视脚本安...
分享一款!wepoker怎么挂... 分享一款!wepoker怎么挂底牌,fishpoker透视底牌,总是真的有挂(有挂详情)1)免费钻石...
实测分享!wepoker怎么拿... 实测分享!wepoker怎么拿到好牌,werplan透视挂,竟然真的有挂(有挂技术)1)免费钻石:进...
每日必看!wepoker私人局... 每日必看!wepoker私人局规律,hhpoker辅助,一贯存在有挂(真是有挂)1、进入到是否有挂之...
推荐一款!aapoker脚本怎... 推荐一款!aapoker脚本怎么用,pokemmo手机辅助软件,一直是有挂(存在有挂)破解侠是真的助...
科普攻略!德州真人透视脚本,h... 科普攻略!德州真人透视脚本,hhpoker可以控制吗,果然有挂(有挂教学)1、实时透视辅助更新:用户...
专业讨论!来玩app 德州 辅... 专业讨论!来玩app 德州 辅助,wepoker新号好一点吗,一直真的有挂(有挂头条)1)免费钻石:...
一分钟快速了解!aapoker... 一分钟快速了解!aapoker透视方法,wejoker透视方法,真是是有挂(有挂教程);1、超多福利...
解密关于!wepoker有人用... 解密关于!wepoker有人用过吗,wepoker怎么开辅助,一贯存在有挂(今日头条)1、首先打开辅...
分享开挂内幕!wepoker新... 分享开挂内幕!wepoker新号好一点吗,德普之星辅助工具如何打开,一贯真的是有挂(有挂详细)1)辅...