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

发布于 2024-10-14 21:01:03 字数 4176 浏览 3 评论 0原文

我想使用 HttpURLConnection 进行 POST。 我正在以两种方式尝试此操作,但是在执行以下操作时我总是会遇到异常: conn.getOutputStream();

在这两种情况下我得到的异常是:

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

功能 1:

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();
    }


}

I want to make a POST by using HttpURLConnection.
I am trying this in 2 ways, but I always get an excetion when doing: conn.getOutputStream();

The exception I get in both cases is:

java.net.SocketException: Operation timed out: connect:could be due to
invalid address

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();
    }
}

or function 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();
    }


}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木槿暧夏七纪年 2024-10-21 21:01:03

该 URL 根本无法访问。 URL 错误,或者 DNS 服务器无法解析主机名。尝试使用众所周知的 URL 进行简单连接以排除其中一个或另一个,例如

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");

在运行时只执行一次就足够了。

另请参阅:

The URL simply cannot be reached. Either the URL is wrong, or the DNS server couldn't resolve the hostname. Try a simple connect with a well-known URL to exclude one and other, e.g.

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

Update as per the comments, you're required to use a proxy server for HTTP connections. You need to configure that in the Java side as well. Add the following lines before any attempt to connect to an URL.

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

It suffices to do this only once during runtime.

See also:

瑕疵 2024-10-21 21:01:03

如果不建立连接(在这种情况下需要执行 1 个以上的步骤,即连接),则无法进行传输。 connect() 应在连接配置后调用(即在连接上使用 set***() 后)。

缺少的是:

conn.connect();

Without establishing the connection (which in this case requires 1 more step to be performed ie connect), transfer is not possible. connect() should be called after the connection is configured (ie after being done with the set***() on the connection).

What is missing is:

conn.connect();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文