Android文件上传带参数

//返回值HttpResult可替换成自己想要的类型.
public static <T> HttpResult post(final String urlStr, final Map params, T body) {
    String BOUNDARY = UUID.randomUUID().toString();  //边界标识   随机生成
    String PREFIX = "--", LINE_END = "\r\n";
    HttpResult result = new HttpResult<>();

    File file = (File) body;
    HttpURLConnection conn = null;
    try {
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(30 * 1000);
        conn.setConnectTimeout(30 * 1000);
        conn.setDoInput(true);  //允许输入流
        conn.setDoOutput(true); //允许输出流
        conn.setUseCaches(false);  //不允许使用缓存
        conn.setRequestMethod("POST");  //请求方式
        conn.setRequestProperty("Charset", CHARSET);  //设置编码
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data" + ";boundary=" + BOUNDARY);
        headers.remove("token");

        OutputStream out = conn.getOutputStream();
        StringBuffer sb = new StringBuffer();
        for (Map.Entry entry : params.entrySet()) {
            sb.append(PREFIX).append(BOUNDARY).append(LINE_END)
                    .append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END)
                    .append("Content-Type: text/plain; charset=" + CHARSET + LINE_END)
                    .append("Content-Transfer-Encoding: 8bit" + LINE_END)
                    .append(LINE_END).append(entry.getValue()).append(LINE_END);
        }
        sb.append(PREFIX).append(BOUNDARY).append(LINE_END)
                .append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + LINE_END)
                .append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END)
                .append(LINE_END);
        out.write(sb.toString().getBytes(CHARSET));

        InputStream is = new FileInputStream(file);
        byte[] bytes = new byte[1024];
        int len;
        while ((len = is.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }
        out.write(LINE_END.getBytes());
        out.write((PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes());
        out.flush();

        is.close();
        out.close();

        int resCode = result.code = conn.getResponseCode(); // 开始发送数据
        if (resCode == RES_CODE_SUCCESS) {
            result.obj = buildString(conn.getInputStream());
        }
    } catch (IOException e) {
        e.printStackTrace();
        result.e = e;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return result;
}

你可能感兴趣的:(1)