Exemple #1
0
  public static boolean uploadFile(
      String url, String uploadKey, File file, Map<String, String> params) {
    // TODO httpClient连接关闭问题需要考虑
    try {
      HttpPost httppost = new HttpPost("http://www.new_magic.com/service.php");

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart(uploadKey, new FileBody(file));
      for (Map.Entry<String, String> entry : params.entrySet()) {
        StringBody value = new StringBody(entry.getValue());
        reqEntity.addPart(entry.getKey(), value);
      }

      httppost.setEntity(reqEntity);
      HttpResponse response = httpClient.execute(httppost);
      int statusCode = response.getStatusLine().getStatusCode();

      if (statusCode == HttpStatus.SC_OK) {
        HttpEntity resEntity = response.getEntity();
        String body = EntityUtils.toString(resEntity);
        EntityUtils.consume(resEntity);

        Map<String, Object> responseMap = JsonUtil.parseJson(body, Map.class);
        if (responseMap.containsKey("code") && responseMap.get("code").equals(10000)) {
          return true;
        }
      }
    } catch (Exception e) {
      log.error("", e);
    }
    return false;
  }