0

我按照本教程进行操作,但不是得到 200,而是总是得到 302 作为服务器响应。

导读

有人可以检查一下吗?

4

2 回答 2

0

我在我的应用程序中使用了此代码。它的工作。它可能会帮助你。

private String doFileUpload() {

    final DataOutputStream dos;

    String exiting_file_path = filePath;
    String boundary = "*****";
    String twohypens = "--";
    String lineend = "\r\n";
    int maxBufferSize = 1 * 1024 * 1024;
    int buferSize;
    int bytesRead;
    String url_string = "your URL";

    try {
        Log.d("Debug", "Start Uploading");
        FileInputStream fileInStream = new FileInputStream(
                exiting_file_path);
        URL url = new URL(url_string);
        httpUrlConn = (HttpURLConnection) url.openConnection();

        httpUrlConn.setDoInput(true);
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestMethod("POST");
        httpUrlConn.setRequestProperty("connection", "Keep-Alive");
        httpUrlConn.setRequestProperty("content-type",
                "multipart/form-data;boundary=" + boundary);

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

        dos.writeBytes(twohypens + boundary + lineend);
        dos.writeBytes("content-disposition:form-data; name=\"upload_file\"; filename=\""
                + exiting_file_path + "\"" + lineend);
        dos.writeBytes(lineend);

        int buferAvailable = fileInStream.available();
        buferSize = Math.min(buferAvailable, maxBufferSize);
        final byte[] buffer = new byte[buferSize];

        bytesRead = fileInStream.read(buffer, 0, buferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, buferSize);
            buferAvailable = fileInStream.available();
            buferSize = Math.min(buferAvailable, maxBufferSize);
            bytesRead = fileInStream.read(buffer, 0, buferSize);
        }
        dos.writeBytes(lineend);
        dos.writeBytes(twohypens + boundary + twohypens + lineend);
        fileInStream.close();
        dos.flush();
        dos.close();

    } catch (FileNotFoundException e) {
        Toast.makeText(getApplicationContext(), "" + e, 1).show();
        e.printStackTrace();
    } catch (MalformedURLException e) {
        Toast.makeText(getApplicationContext(), "" + e, 1).show();
        e.printStackTrace();
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "" + e, 1).show();
        e.printStackTrace();
    }

    try {
        DataInputStream inStream = new DataInputStream(
                httpUrlConn.getInputStream());

        while ((STRRRR = inStream.readLine()) != null) {
            Log.d("Debug", "Server Response " + STRRRR);
        }
        inStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return STRRRR;
}
于 2012-05-08T05:05:52.263 回答
0

您很可能对 URL 做了一些有趣的事情,例如将其指定为“http://example.com”,然后服务器立即使用重定向代码 302 将您重定向到“http://example.com/”(注意末尾的斜杠) .

检查服务器返回的标头,它通常包含正确的位置。

于 2012-05-08T05:35:53.587 回答