Exemplo n.º 1
0
  /**
   * 下载图片
   *
   * @param url 图片的Url
   * @param context 上下文
   * @param savePath 保存路径 (目录)为空表示不保存
   * @param imagefile 图片文件名称 如果为空则以url的图片名称做文件名称 只接受 .png和.jpg后缀路径
   * @param callback 回调
   * @return
   */
  public static CustomRunnable<String, LoadImageRespone> downLoadImage(
      String url,
      final Context context,
      String savePath,
      final String imagefileName,
      final DownloadCallback callback) {
    if (url == null) {
      return null;
    }
    CustomRunnable<String, LoadImageRespone> customRunnable =
        new CustomRunnable<String, LoadImageRespone>(new String[] {url, savePath}) {
          @Override
          public LoadImageRespone executeTask(String... param) {

            String uri = param[0];
            if (uri == null) {
              return new LoadImageRespone();
            }
            String savePath = null;
            if (param.length > 1) {
              savePath = param[1];
            }
            DefaultHttpClient client = new DefaultHttpClient();
            HttpParams httParams = client.getParams();
            HttpConnectionParams.setConnectionTimeout(httParams, 20000);
            HttpConnectionParams.setSoTimeout(httParams, 20000);

            HttpProtocolParams.setContentCharset(httParams, HTTP.UTF_8);
            HttpProtocolParams.setUseExpectContinue(httParams, false);
            if (OrongApplication.cookieStore != null) {
              client.setCookieStore(OrongApplication.cookieStore);
            }
            HttpGet get = new HttpGet(uri);
            LoadImageRespone respone = null;

            try {
              HttpResponse responese = client.execute(get);
              int responeseCode = responese.getStatusLine().getStatusCode();
              if (responeseCode == HttpStatus.SC_OK) {
                HttpEntity httpentity = responese.getEntity();
                InputStream imStream = httpentity.getContent();
                Bitmap bitmap = BitmapFactory.decodeStream(imStream);
                respone = new LoadImageRespone(bitmap);
                if (savePath != null) {
                  File dire = FileUitls.createDirectory(context, savePath);
                  if (dire.exists()) {
                    String fileName = null;
                    if (imagefileName != null
                        && (imagefileName.endsWith(".jpg") || imagefileName.endsWith(".png"))) {
                      fileName = "/" + imagefileName;
                    } else {
                      fileName = uri.substring(uri.lastIndexOf("/"));
                    }
                    File file = new File(dire + fileName);
                    if (!file.exists()) {
                      file.createNewFile();
                      FileOutputStream out = new FileOutputStream(file);
                      if (bitmap != null) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                      }
                      out.flush();
                      out.close();
                    }

                    respone.setFileSavePath(file);
                  }
                }
              }
            } catch (ClientProtocolException e) {
              e.printStackTrace();
            } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            return respone;
          }

          @Override
          public void beforTask() {
            // TODO Auto-generated method stub
            callback.beforeDownload();
            super.beforTask();
          }

          @Override
          public void afterTask(LoadImageRespone result) {
            callback.loadCompleteCallback(result);
            super.afterTask(result);
          }
        };
    ThreadPoolService.execute(customRunnable);
    return customRunnable;
  }
Exemplo n.º 2
0
  public static CustomRunnable<?, ?> imageUpload(UpLoadDatas datas, final UploadCallback callback) {
    CustomRunnable<UpLoadDatas, String> customRunnable =
        new CustomRunnable<UpLoadDatas, String>(datas) {
          @Override
          public String executeTask(UpLoadDatas... param) {
            UpLoadDatas upLoadDatas = param[0];
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpParams httParams = httpclient.getParams();
            HttpConnectionParams.setConnectionTimeout(httParams, 20000);
            HttpConnectionParams.setSoTimeout(httParams, 20000);
            HttpProtocolParams.setContentCharset(httParams, HTTP.UTF_8);
            HttpProtocolParams.setUseExpectContinue(httParams, false);
            if (OrongApplication.cookieStore != null) {
              httpclient.setCookieStore(OrongApplication.cookieStore);
            }
            // 设置通信协议版本
            httpclient
                .getParams()
                .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpPost httppost = new HttpPost(upLoadDatas.getUrl());
            File file = upLoadDatas.getImageFile();

            MultipartEntity mpEntity = new MultipartEntity(); // 文件传输
            ContentBody cbFile = new FileBody(file);
            StringBody imageStr = null;
            StringBody mothodStr = null;
            ArrayList<BasicNameValuePair> paramList = upLoadDatas.getParamList();
            try {
              imageStr = new StringBody("image");
              mpEntity.addPart("upType", imageStr);
              if (paramList != null) {
                for (BasicNameValuePair valuePair : paramList) {
                  mpEntity.addPart(valuePair.getName(), new StringBody(valuePair.getValue()));
                }
              }
            } catch (UnsupportedEncodingException e1) {
              // TODO Auto-generated catch block
              e1.printStackTrace();
            }
            mpEntity.addPart("fileData", cbFile);
            // mpEntity.addPart(file.getName(), cbFile); // <input
            // type="file"
            // name="userfile"
            // /> 对应的
            System.out.println(file.getName());
            httppost.setEntity(mpEntity);
            HttpResponse responese;
            String result = null;
            try {
              responese = httpclient.execute(httppost);
              int responeseCode = responese.getStatusLine().getStatusCode();
              if (responeseCode == HttpStatus.SC_OK) {

                result = EntityUtils.toString(responese.getEntity(), HTTP.UTF_8);
                System.out.println(result);
                return result;
              } else if (399 < responeseCode && responeseCode < 500) { // 请求无响应拒绝等
                return String.valueOf(Constant.NO_RESPONSE);
              } else if (500 <= responeseCode && responeseCode < 600) { // 服务器出错出现异常
                return String.valueOf(Constant.S_EXCEPTION);
              } else { // 其它异常
                return String.valueOf(Constant.RESPONESE_EXCEPTION);
              }
            } catch (ClientProtocolException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } catch (ConnectTimeoutException e) {
              e.printStackTrace();
              return String.valueOf(Constant.TIMEOUT);
            } catch (UnknownHostException e) {
              // 网络状态是否可用
              if (!NetUtils.isHasNet(upLoadDatas.getContext())) {
                return String.valueOf(Constant.NO_NETWORK); // 无可用网络
              } else {
                e.printStackTrace();
                return String.valueOf(Constant.RESPONESE_EXCEPTION);
              }

            } catch (IOException e) {
              e.printStackTrace();
              return String.valueOf(Constant.RESPONESE_EXCEPTION);
            }
            httpclient.getConnectionManager().shutdown();
            return result;
          }

          @Override
          public void beforTask() {
            // TODO Auto-generated method stub
            callback.beforeUpload();
            super.beforTask();
          }

          @Override
          public void afterTask(String result) {
            callback.afterUpload(result);
            super.afterTask(result);
          }
        };
    ThreadPoolService.execute(customRunnable);
    return customRunnable;
  }