0

我知道 Stackoverflow 上有类似的问题,但它们并没有解决我的问题。我想将文件从 android 上传到本地 apache 服务器,但出现“连接被拒绝”错误。

我在 Mac OS X Lion(端口 80 上的 Apache)上使用带有 Android 3.2 和 MAMP 的物理设备。我还在清单中添加了 INTERNET 权限。

这是代码:

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(new File(
                "/mnt/sdcard/somefile.xml"));
    } catch (FileNotFoundException e) {
        ...
    }

    URL url = null;
    try {
        url = new URL("http://192.168.x.xxx:80/index.php");
    } catch (MalformedURLException e) {
        ...
    }

    try {
        // Open a HTTP connection to the URL
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Connection", "Keep-Alive");

        conn.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                + SOMEFILE + "" + lineEnd);
        dos.writeBytes(lineEnd);

        // create a buffer of maximum size
        int bytesAvailable = fileInputStream.available();
        int maxBufferSize = 1000;
        // int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bytesAvailable];

        // read file and write it into form...
        int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bytesAvailable);
            bytesAvailable = fileInputStream.available();
            bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (IOException e) {
        ...
    }

例外:

07-24 14:48:43.280: E/App(5802): failed to upload file '/mnt/sdcard/somefile.xml' to   
server 'http://192.168.x.xxx:80/index.php'
07-24 14:48:43.280: E/App(5802): java.net.ConnectException: /192.168.x.xxx:80 -   
Connection refused
4

2 回答 2

1

您是否在 Mac 上启用并运行了防火墙?

确定端口 80 是否真的打开的最佳方法(恕我直言)是在本地网络上的另一台机器上针对目标地址运行 NMap(或 gui Zenmap)。

如果它只是您的台式机和您的 Android 设备,您可以尝试浏览到http://192.168.xx以查看 Apache 服务器是否正在给出响应。

于 2012-07-24T14:54:51.017 回答
1

代码似乎没问题。模拟器可以毫无问题地连接。路由器防火墙有问题

于 2012-07-25T07:13:53.093 回答