3

HttpURLConnection を使用して POST を作成したいと考えています。私はこれを2つの方法で試していますが、実行すると常に例外が発生します: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();
    }


}
4

2 に答える 2

8

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

これは、実行時に 1 回実行するだけで十分です。

以下も参照してください。

于 2011-01-27T13:26:30.947 に答える
2

接続を確立しないと (この場合、さらに 1 ステップ実行する必要があります)、転送はできません。connect()接続が構成された後 (つまり、接続で を実行した後) に呼び出す必要がありますset***()

欠けているものは次のとおりです。

conn.connect();
于 2012-07-10T08:04:02.623 に答える