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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章