如何在HttpURLConnection上设置Entity

Kno*_*uch 7 java

在我的项目中,我必须严格使用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);
Run Code Online (Sandbox Code Playgroud)

问题是我不能使用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(url=@TargetFileName,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;
      }
}
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误

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)
Run Code Online (Sandbox Code Playgroud)

Nai*_*ili 2

要使用 HttpURLConnection 发布文件,您必须手动编写文件包装器。看看这个答案,应该对你有帮助。