2014-04-01 23 views
7

setEntity在我的項目,我必須嚴格使用HttpURLConnection的類如何在HttpURLConnection的

我有我從互聯網

MultipartEntity multiPart = new MultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null Chartset.forName("UTF-8"); 
File f = new File("/home/abhishek/foo.docx"); 
FileBody fb = new FileBody(f); 
multiPart.addPart("file", fb); 
HttpPost post = new HttpPost(); 
post.setHeader("ENCTYPE", "multipart/form-data"); 
post.setEntity(multiPart); 

問題得到這個下面的代碼是我不能使用HttpPost ...在我的項目中只有HttpURLConnection類的作品!

所以我需要將上面的代碼翻譯成HttpURLConnection。

我在HttpUrlConnection上找不到類似於setEntity的任何東西。

編輯::

根據以下建議。我有這樣的代碼

public class RESTFileUpload { 
     public static void main(String[] args) throws Exception { 
      Authenticator.setDefault(new Authenticator() { 
       @Override 
       public PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication("domain\\user", "Password".toCharArray()); 
       } 
      }); 

      String filePath = "/home/abhishek/Documents/HelloWorld.docx"; 
      String fileName = "HelloWorld.docx"; 
      String fileNameShort = "HelloWorld"; 

      String urlStr = "https://sp.company.com/sites/abhi_test/_vti_bin/listdata.svc/SharedDocuments/RootFolder/Files/add([email protected],overwrite='true')&@TargetFileName=" + fileName; 
      String crlf = "\r\n"; 
      String twoHypens = "--"; 
      String boundary = "*****"; 
      URL url = new URL(urlStr);   
      HttpURLConnection con = (HttpURLConnection) url.openConnection();   
      con.setDoOutput(true); 
      con.setDoInput(true);  
      con.setUseCaches(false); 
      con.setRequestMethod("POST"); 
      con.setRequestProperty("Connection", "Keep-Alive"); 
      con.setRequestProperty("Cache-Control", "no-cache"); 
      con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 
      DataOutputStream request = new DataOutputStream(con.getOutputStream()); 
      request.writeBytes(twoHypens + boundary + crlf); 
      request.writeBytes("Content-Disposition: form-data;name=\"" + fileNameShort + "\";fileName=\"" + fileName + "\"" + crlf); 
      request.writeBytes(crlf); 
      request.write(convertToByteArray(filePath)); 
      request.writeBytes(crlf); 
      request.writeBytes(twoHypens + boundary + twoHypens + crlf); 
      request.flush(); 
      request.close(); 

      InputStream responseStream = new BufferedInputStream(con.getInputStream()); 
      BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream)); 
      String line = ""; 
      StringBuilder strBuilder = new StringBuilder(); 
      while((line = responseStreamReader.readLine()) != null) { 
       strBuilder.append(line).append("\n"); 
      } 
      responseStreamReader.close(); 
      String response = strBuilder.toString(); 
      responseStream.close(); 
      con.disconnect(); 
      System.out.println(response); 
     } 

     private static byte[] convertToByteArray(String filePath) { 
      File f = new File(filePath); 
      byte[] retVal = new byte[(int)f.length()]; 
      try { 
       FileInputStream fis = new FileInputStream(f); 
       fis.read(retVal); 
      } 
      catch (FileNotFoundException ex) { 
       ex.printStackTrace(); 
      } 
      catch(IOException ex2) { 
       ex2.printStackTrace(); 
      } 
      return retVal; 
     } 
} 

但我得到的錯誤

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://sp.web.gs.com/sites/abhi_test/_vti_bin/listdata.svc/SharedDocuments/ 
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1626) 
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) 
    at RESTFileUpload.main(RESTFileUpload.java:62) 

回答

2

要使用HttpURLConnection發佈文件,您必須手動組合文件包裝。看看這個answer,它應該對你有幫助。

+0

謝謝。我根據您的建議更改了代碼...但是收到了400錯誤消息 –

+0

您是否嘗試通過讀取錯誤流來查看400響應代碼後面的錯誤消息? 'httpConnection.getErrorStream();' – Naili

+0

error stream says ...此頁面的安全驗證無效,可能已損壞。請使用您的網絡瀏覽器的後退按鈕再次嘗試您的操作 –

3

HttpURLConnection的具有.getInputStream()和.getOutputStream()方法。如果您希望使用Http請求發送主體內容,請在您的HttpURLConnection對象上調用.setDoOutput(true),調用.getOutputStream()以獲取輸出流,然後將實體的內容寫入輸出流(原始字節,或使用某種類型的Writer實現),在完成寫作時關閉它。

有關更多詳細信息,請參閱HttpURLConnection here的API文檔。

+0

謝謝。我根據您的建議更改了代碼,但它給了我一個400錯誤信息 –

相關問題