【问题标题】:How to setEntity on a HttpURLConnection如何在 HttpURLConnection 上设置实体
【发布时间】:2014-05-11 13:47:57
【问题描述】:

在我的项目中我必须严格使用 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)

【问题讨论】:

    标签: java


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢。我根据您的建议更改了代码,但它给了我 400 错误消息
    【解决方案2】:

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

    【讨论】:

    • 谢谢。我根据您的建议更改了代码...但收到 400 错误消息
    • 您是否尝试通过读取错误流来查看 400 响应代码背后的错误消息? httpConnection.getErrorStream();
    • 错误流说...此页面的安全验证无效并且可能已损坏。请使用您的网络浏览器的返回按钮再次尝试您的操作
    猜你喜欢
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多