有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将请求放入post文件

我正在编写一个java程序,需要向url发送PUT请求。我通过使用

cURL -k -T myFile -u username:password https://www.mywebsite.com/myendpoint/

但是,如果我可以简单地在java代码中执行请求,那就更好了。到目前为止,我的java代码是

public static Integer sendFileToEndpoint(java.io.File file, String folder) throws Exception
{
    java.net.URL url = new java.net.URL("https://www.mywebsite.com/" + folder);
    java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);

    java.io.FileInputStream fis = new java.io.FileInputStream(file);
    byte [] fileContents = org.apache.commons.io.IOUtils.toByteArray(fis);

    String authorization = "Basic " + new String(new org.apache.commons.codec.binary.Base64().encode("username:password".getBytes()));

    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Authorization", authorization);
    conn.setRequestProperty("User-Agent","curl/7.37.0");
    conn.setRequestProperty("Host", "www.mywebsite.com");
    conn.setRequestProperty("Accept","*/*");
    conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length));
    conn.setRequestProperty("Expect","100-continue");

    if(conn.getResponseCode() == 100)
    {
        //not sure what to do here, but I'm not getting a 100 return code anyway
        java.io.OutputStream out = conn.getOutputStream();
        out.write(fileContents);
        out.close();
    }
    return conn.getResponseCode();
}

我得到一个411返回码。我明确地设置了内容长度,所以我不明白。响应的标题为:

HTTP/1.1 411 Length Required
Content-Type:text/html; charset=us-ascii
Server:Microsoft-HTTPAPI/2.0
Date:Wed, 27 Aug 2014 16:32:02 GMT
Connection:close
Content-Length:344

起初,我发送带有标题的正文,得到了一个409错误。所以,我看了一下cURL在做什么。他们单独发送报头,期望返回100码。一旦他们得到100的回复,他们发送身体,得到200的回复

我在java中发送的头似乎与cURL发送的头相同,但我得到的是411返回代码,而不是100。知道怎么了吗


共 (2) 个答案

  1. # 1 楼答案

    您应该查看http客户端库,例如Apache HTTP Components。这样你就可以在更高的层次上工作,希望你不必担心计算内容长度

  2. # 2 楼答案

    替换

    java.net.URL url = new java.net.URL("https://www.mywebsite.com/" + folder);
    

    java.net.URL url = new java.net.URL("https://www.mywebsite.com/" + folder + file.getName());
    

    此外,您不需要等待100响应发送身体