2014-02-12 86 views
0
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; 

}POST休息呼叫在Java

我使用上述方法来上传利用休息呼叫一个文件(.pak)附加文件。我在这里做的任何错误?使用Crome浏览器的其余客户端工具,我可以做到。我只是把附加文件的POST请求和我附加文件的字段名称是“内容”。

+0

这是抛出500错误,当我删除使用任何“内容类型”投掷406错误。 –

+0

检查服务器端日志(如果它们对您可用)。 – Santosh

+0

我可以使用浏览器休息客户端工具进行调用。 –

回答

0

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