Android HTTP-Connection挂起在connection.getOutputStream();

时间:2014-05-10 14:01:29

标签: android http post file-upload

 connection = (HttpURLConnection) url.openConnection();
    // Allow Inputs & Outputs.
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    // Set HTTP method to POST.
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
    outputStream = new DataOutputStream( connection.getOutputStream() ); //HERE IT STOPS WORKING WITHOUT AN ERROR

我使用的是ADT而没有使用仿真器(直接连接到我的智能手机)。如果我通过浏览器直接通过HTML请求上传文件,则文件上传有效。我有什么想法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

使用我的上传方法

    private void doFileUpload() {
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;// 1 MB
    String responseFromServer = "";
    String urlString = Constant.URL + "upload_fil.php";
    try {
        // ------------------ CLIENT REQUEST
        FileInputStream fileInputStream = new FileInputStream(new File(
                selectedPath));
        // open a URL connection to the Servlet
        URL url = new URL(urlString);
        // Open a HTTP connection to the URL
        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);
        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                + imageName + "\"" + lineEnd);

        Log.i(TAG, "Uploading starts");
        dos.writeBytes(lineEnd);
        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            Log.i(TAG, "Uploading");
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
        // send multipart form data necesssary after file data...

        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        // close streams
        Log.e("Debug", "File is written");

        Log.i(TAG, "Uploading ends");

        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    // ------------------ read the SERVER RESPONSE
    try {
        inStream = new DataInputStream(conn.getInputStream());
        String str;

        while ((str = inStream.readLine()) != null) {
            Log.e("Debug", "Server Response " + str);
            onUploadComplete();
            try {
                final JSONObject jsonObject = new JSONObject(str);
                if (jsonObject.getBoolean("status")) {
                    handler.post(new Runnable() {
                        public void run() {
                            try {
                                Toast.makeText(getApplicationContext(),
                                        jsonObject.getString("message"),
                                        Toast.LENGTH_SHORT).show();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });
                } else {
                    handler.post(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Toast.makeText(getApplicationContext(),
                                        jsonObject.getString("message"),
                                        Toast.LENGTH_SHORT).show();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        inStream.close();

    } catch (IOException ioex) {
        ioex.printStackTrace();
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
}