1. 程式人生 > >HttpClient上傳圖片,下載檔案

HttpClient上傳圖片,下載檔案

 /**
     * 上傳圖片到伺服器
     * @param webPath  伺服器處理地址
     * @param uploadFilePath  上傳檔案地址
     * @return
     */
    public static String uploadFile(String webPath,String uploadFilePath) {

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(webPath);
        try {
            File osFile = new File(uploadFilePath);
            if (!osFile.exists()) {
                return null;
            }
            FileBody fileBody = new FileBody(osFile);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            // image 是服務端讀取檔案的 key
            entity.addPart("image", fileBody);
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            if(status == HttpStatus.SC_OK){
                //獲取伺服器返回結果
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                Log.e("MyLog", "返回結果:" + result);
                return  result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 /**
     * 實現網路訪問檔案,將獲取到的資料儲存在指定目錄中
     * @param url 訪問網路的url地址
     * @param destFile 儲存的檔案
     * @return
     */
    public static boolean loadFileFromURL(String url,File destFile) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet requestGet = new HttpGet(url);
        HttpResponse httpResponse = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(destFile));
            httpResponse = httpClient.execute(requestGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = httpResponse.getEntity();
                bis = new BufferedInputStream(entity.getContent());
                int len = -1;
                byte[] buffer = new byte[8 * 1024];
                while ((len = bis.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                    bos.flush();
                }
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }