2014-02-12 122 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代碼的內容。你應該看到一些不同的東西,如缺少標題或類似的東西。服務器可以包含各種業務邏輯,並可以因爲數百萬個原因拒絕您的請求。