Android http附带参数的文件上传

/**
 *
 * @param urlString 路径
 * @param params 上传参数
 * @param files 上传文件
 * @return 返回结果
 * @throws IOException
 */

public static String doPost(String urlString, Map<String, Object> params,
                          Map<String, byte[]> files) throws IOException {

    String BOUNDARY = java.util.UUID.randomUUID().toString();
    String PREFIX = "--", LINEND = "\r\n";
    String MULTIPART_FROM_DATA = "multipart/form-data";
    String CHARSET = "UTF-8";

    URL uri = new URL(urlString+encodeParams(params));
    HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
    conn.setReadTimeout(10 * 1000);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "keep-alive");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
            + ";boundary=" + BOUNDARY);

    DataOutputStream outStream = new DataOutputStream(
            conn.getOutputStream());
    if (files != null) {
        for (Map.Entry<String, byte[]> file : files.entrySet()) {
            StringBuilder sb1 = new StringBuilder();
            sb1.append(PREFIX);
            sb1.append(BOUNDARY);
            sb1.append(LINEND);
            sb1.append("Content-Disposition: form-data; name=\"userupfile\"; filename=\""
                    + file.getKey() + "\"" + LINEND);
            sb1.append("Content-Type: application/octet-stream; charset="
                    + CHARSET + LINEND);
            sb1.append(LINEND);
            outStream.write(sb1.toString().getBytes());
            outStream.write(file.getValue());
            outStream.write(LINEND.getBytes());
        }
    }

    byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
    outStream.write(end_data);
    outStream.flush();

    int res = conn.getResponseCode();
    String in = null;
    if (res == HttpURLConnection.HTTP_OK) {
        in = getStringFromStream(conn.getInputStream());
    }
    return in;
}

 
//     Accept: text/plain, */*
//  Accept-Language: zh-cn
//  Host: 192.168.24.56
//  Content-Type:multipart/form-data;boundary=-----------------------------7db372eb000e2
//  User-Agent: WinHttpClient
//  Content-Length: 3693
//  Connection: Keep-Alive
//  -------------------------------7db372eb000e2
//  Content-Disposition: form-data; name="file"; filename="kn.jpg"
//  Content-Type: image/jpeg
//  (此处省略jpeg文件二进制数据...)
//  -------------------------------7db372eb000e2--
/**
 * 本方法需要导入httpmime的jar包
 *
 * @param urlPath 请求路径
 * @param params  上传参数 
 * @param files 上传文件的本地路径 
 * @return 服务器返回结果 
 * @throws IOException
 */
public static String doPostByHttpClient(String urlPath, Map<String, Object> params, Map<String, String> files) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(urlPath);
    MultipartEntity mpEntity = new MultipartEntity();
    for (Map.Entry<String, String> file : files.entrySet()) {
        ContentBody cbFile = new FileBody(new File(file.getValue()));
        mpEntity.addPart(file.getKey(), cbFile);
    }
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        mpEntity.addPart(entry.getKey(), new StringBody((String) entry.getValue(), "text/plain", Charset.forName("UTF-8")));
    }
    post.setEntity(mpEntity);
    String res = null;
    HttpResponse response = client.execute(post);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        res = getStringFromStream(response.getEntity().getContent());
    }
    String content = EntityUtils.toString(response.getEntity());
    client.getConnectionManager().shutdown();
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值