1

我正在尝试使用 HttpURLConnection.getOutputStream() 写入我的 Web 服务器上的文本文件。我已经在两台不同的服务器上尝试过,但没有成功。

我添加了一个 FileWriter 来测试 InputStream,并且该文件在本地目录中正确创建,但 Web 服务器目录中没有显示任何内容,即使所有密码保护都已关闭。

任何帮助将不胜感激。

URL url;
    try {
        url = new URL("http://www.myWebsite.com/myFile.txt");

           HttpURLConnection urlConnection = null;

            try {
                urlConnection = (HttpURLConnection) url.openConnection();


                try {
                    urlConnection.setDoOutput(true);
                    urlConnection.setDoInput(true);


                    OutputStream in = new BufferedOutputStream(urlConnection.getOutputStream());

                     InputStream fin1;
                        try {
                            fin1 = new FileInputStream(Environment.getExternalStorageDirectory() + "/fileToRead.txt");
                            FileWriter fWriter = new FileWriter(Environment.getExternalStorageDirectory() + "/fileToWrite.txt");

                            int data = fin1.read();
                            while(data != -1) {

                            fWriter.write(data);
                            in.write(data);
                              data = fin1.read();
                            }



                            fWriter.flush();
                            fWriter.close();

                            fin1.close();

                            in.flush();
                            in.close();

                        } catch (FileNotFoundException e31) {
                            // TODO Auto-generated catch block
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                    }
                   } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                                        }
                    finally {
                     urlConnection.disconnect();
                   }
            } catch (IOException e4) {
                                    // TODO Auto-generated catch block
                e4.printStackTrace();
            }
    } catch (MalformedURLException e4) {
        // TODO Auto-generated catch block
        e4.printStackTrace();
    }
4

3 回答 3

1

您必须在 urlConnection 上调用 getInputStream() 才能让输出流将套接字刷新到远程服务器。

请参阅此处的讨论:为什么必须调用 URLConnection#getInputStream 才能写入 URLConnection#getOutputStream?

于 2011-02-05T03:27:15.953 回答
0

您正在捕获 IOException(就在 IOException 之后),但没有对它做任何事情。至少打印堆栈跟踪。

于 2011-02-05T03:28:15.517 回答
0

也可以使用 Apache 的 Http Client http://hc.apache.org/httpcomponents-client-ga/index.html

比让 URLConnection 工作容易得多。

于 2011-02-05T03:59:41.067 回答