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;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值