Java 如何在HttpURLConnection上设置实体

Java 如何在HttpURLConnection上设置实体,java,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); multiP

在我的项目中,我必须严格使用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(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;
      }
}
但是我得到了错误

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)

HttpURLConnection具有.getInputStream()和.getOutputStream()方法。如果希望通过Http请求发送正文内容,可以在HttpURLConnection对象上调用.setDoOutput(true),调用.getOutputStream()以获取输出流,然后将实体的内容写入输出流(作为原始字节或使用某种写入器实现),在完成写入后将其关闭


有关更多详细信息,请参阅HttpURLConnection的API文档。

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

谢谢。我根据你的建议更改了代码。。。但是我收到了一条400错误信息你是否试图通过读取错误流来查看400响应代码背后的错误信息<代码>httpConnection.getErrorStream()错误流显示。。。此页的安全验证无效,可能已损坏。请使用web浏览器的“后退”按钮再次尝试您的操作。我按照你的建议更改了代码,但它给了我400个错误消息