2012年1月18日 星期三

HttpClient 檔案上傳 + 參數


如果想在HttpClient上使用上傳檔案加上參數,使用MultipartEntity物件。

使用方式如下:

HttpPost post = new HttpPost(http://localhost/upload.php);

MultipartEntity reqEntity = new MultipartEntity(
       HttpMultipartMode.BROWSER_COMPATIBLE);

FileBody bin = new FileBody(new File(/mnt/sdcard/test.zip));

Charset chars = Charset.forName("UTF-8");

try {

    reqEntity.addPart("參數名稱", new StringBody("參數內容",chars));

    reqEntity.addPart("FileUpload1", bin );

    post.setEntity(reqEntity);

    HttpResponse response = httpClient.execute(post);

    HttpEntity entity = response.getEntity();

    if(entity == null){
        return ;
    }

    InputStream is = entity.getContent();

    BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));

    String str = br.readLine();


    //印出回傳結果
    System.out.println(str);
}catch (Exception e) {


    e.printStackTrace();

}