HttpURLConnection POST,conn.getOutputStream() 抛出异常

3
我想使用HttpURLConnection进行POST请求。我正在尝试两种方法,但无论哪种方式,当执行conn.getOutputStream();时,我总是会得到一个异常。
我在两种情况下都收到相同的异常消息:

java.net.SocketException: 操作超时: 连接: 可能由于无效地址

function1:
public void makePost(String title, String comment, File file) {
    try {
        URL servlet = new URL("http://" + "www.server.com/daten/web/test/testupload.nsf/upload?CreateDocument");            
        HttpURLConnection conn=(HttpURLConnection)servlet.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        String boundary = "---------------------------7d226f700d0";
        conn.setRequestProperty("Content-type","multipart/form-data; boundary=" + boundary);
        //conn.setRequestProperty("Referer", "http://127.0.0.1/index.jsp");
        conn.setRequestProperty("Cache-Control", "no-cache");

        OutputStream os = conn.getOutputStream(); //exception throws here!
        DataOutputStream out = new DataOutputStream(os);
        out.writeBytes("--" + boundary + "\r\n");
        writeParam(INPUT_TITLE, title, out, boundary);
        writeParam(INPUT_COMMENT, comment, out, boundary);
        writeFile(INPUT_FILE, file.getName(), out, boundary);
        out.flush();
        out.close();

        InputStream stream = conn.getInputStream();
        BufferedInputStream in = new BufferedInputStream(stream);
        int i = 0;            
        while ((i = in.read()) != -1) {
            System.out.write(i);            
        }            
        in.close();
    } catch (Exception e) {  
        e.printStackTrace();
    }
}

或者函数 2:

public void makePost2(String title, String comment, File file) {

    File binaryFile = file;
    String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.

    URLConnection connection = null;
    try {
        connection = new URL("http://" + "www.server.com/daten/web/test/testupload.nsf/upload?CreateDocument").openConnection();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    PrintWriter writer = null;
    try {
        OutputStream output = connection.getOutputStream(); //exception throws here
        writer = new PrintWriter(new OutputStreamWriter(output, CHARSET), true); // true = autoFlush, important!

        // Send normal param.
        writer.println("--" + boundary);
        writer.println("Content-Disposition: form-data; name=\""+ INPUT_TITLE +"\"");
        writer.println("Content-Type: text/plain; charset=" + CHARSET);
        writer.println();
        writer.println(title);

//        Send binary file.
        writer.println("--" + boundary);
        writer.println("Content-Disposition: form-data; name=\""+ INPUT_FILE +"\"; filename=\"" + binaryFile.getName() + "\"");
        writer.println("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()));
        writer.println("Content-Transfer-Encoding: binary");
        writer.println();
        InputStream input = null;
        try {
            input = new FileInputStream(binaryFile);
            byte[] buffer = new byte[1024];
            for (int length = 0; (length = input.read(buffer)) > 0;) {
                output.write(buffer, 0, length);
            }
            output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
        }
        writer.println(); // Important! Indicates end of binary boundary.

        // End of multipart/form-data.
        writer.println("--" + boundary + "--");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (writer != null) writer.close();
    }


}

嗨@Blitzkr1eg,你能添加你的方法“writeParam”吗? - Omar Barrera Valentin
不,这是从2011年的。 - AdrianS
2个回答

8

该网址无法访问。可能是因为网址错误或DNS服务器无法解析主机名。尝试连接一个众所周知的网址,排除其他原因,例如:

InputStream response = new URL("http://stackoverflow.com").openStream();
// Consume response.

更新:根据评论,您需要为HTTP连接使用代理服务器。您还需要在Java端进行配置。在尝试连接到URL之前,请添加以下行。

System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");

在运行时只需要执行一次即可。

另请参阅:


java.net.SocketException: Operation timed out: connect:could be due to invalid address 这句话已经说明了一切。 - Christian Kuetbach
我在一个HTML文件中有一个表单,它向完全相同的URL进行POST请求,并且它可以正常工作。这是怎么回事? - AdrianS
1
你的意思是在普通的网络浏览器中吗?如果是这样,它是否使用HTTP代理服务器?如果是这样,你也应该在Java端进行配置。 - BalusC
是的!就是这样!现在尝试。 - AdrianS
好的,我更新了答案,添加了更多关于如何在Java端实现这一点的细节。 - BalusC

2

在建立连接之前(在这种情况下需要执行1个更多的步骤即连接),传输是不可能的。在配置连接后(即在对连接上的set***()操作完成后),应调用connect()

缺少的是:

conn.connect();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接