POST在java中使用附加文件进行休息调用

时间:2014-02-12 05:50:08

标签: java rest

public static InputStream postCallMultipart(String api, String requestBody,
     List<NameValuePair> uploadList) {
  URL url = null;
  InputStream isResponse = null;
  HttpURLConnection httpCon = null;
  OutputStream output = null;
  String charset = "UTF-8";

  MultipartEntity reqEntity =
        new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
  lastCallResponseCode = -1;
  try {

     for (NameValuePair fileUpload : uploadList) {
        String fileName = fileUpload.getName();
        File fileHandler = new File(fileUpload.getValue());
        System.out.println(fileUpload.getValue()+"============"+fileName);
        FileBody fileBody = new FileBody(fileHandler);
        reqEntity.addPart(fileName, fileBody);
     }

     if (null != requestBody && !requestBody.isEmpty()) {
        reqEntity.addPart("rawData", new StringBody(requestBody));
     }

     url = new URL(serverUrl + api);
     Reporter.log("POST: " + url.toString(), true);

     httpCon = (HttpURLConnection) url.openConnection();
     httpCon.setUseCaches(false);
     httpCon.setDoInput(true);
     httpCon.setDoOutput(true); // Triggers POST.
     httpCon.setRequestMethod("POST");
     httpCon.setRequestProperty("Accept",contentType);
     httpCon.setRequestProperty("Accept-Charset", charset);
     httpCon.setRequestProperty("Content-Type", "multipart/form-data");
     httpCon.addRequestProperty("Content-length",
           reqEntity.getContentLength() + "");
     httpCon.addRequestProperty(reqEntity.getContentType().getName(),
           reqEntity.getContentType().getValue());
     httpCon.setRequestProperty("Authorization", HTTP_BASIC_AUTH
           + SINGLE_SPACE + LOCAL_SUPERADMIN_CREDENTIAL_BASE64);
     if(requestHeaders != null){
          for(Entry<String, String> header : requestHeaders.entrySet()){
              httpCon.setRequestProperty(header.getKey(), header.getValue());
          }
     }

     output = httpCon.getOutputStream();
     reqEntity.writeTo(output);
     output.close();
     httpCon.connect();

     lastCallResponseCode = httpCon.getResponseCode();
     isResponse = httpCon.getInputStream();
  } catch (IOException e) {
     isResponse = httpCon.getErrorStream();
     Reporter.log("REST call unsuccessful: " + e.getMessage(), true);
  }
  return isResponse;

}

我使用上面的方法使用rest call上传文件(.pak)。我在这里做的任何错误?使用crome浏览器的其余客户端工具,我能够做到。我只是把POST请求附加文件,我附加文件的字段的名称是“内容”。

1 个答案:

答案 0 :(得分:0)

根据你的评论,你应该嗅探客户端和服务器之间的内容,以便工作的休息客户端和不工作的java代码。你应该看到一些不同的东西,如缺少标题或类似的东西。服务器可以包含各种业务逻辑,并且可以出于数百万原因拒绝您的请求。