如何将参数添加到HttpURLConnection url.openConnection()

时间:2015-06-01 14:00:41

标签: android httpurlconnection

我正在录制视频并按下按钮将其上传到服务器。 同时我需要更新我的数据库中的一个表,该表有2列,名为" userId和filename"。

我跟踪tutorial上传视频,现在我需要将UserId传递给php页面。我不知道该怎么做。

我发现了这个Answer,但是它给出了IOException - stream closed

代码段:

private int uploadFile(String sourceFileUri)     {

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1024 * 1024;

    sourceFileUri = sourceFileUri.replace("file:///","/");
    File sourceFile = new File(sourceFileUri);
    Log.e("Image--sourceFile",""+sourceFile);
    Log.e("Image--sourceFileUri", "" + sourceFileUri);

    if (!sourceFile.isFile())
    {
        dialog.dismiss();
        Log.e("uploadFile", "Source File not exist :" + fileUri);
        runOnUiThread(new Runnable() {
            public void run() {
              //  txtPercentage.setText("Source File not exist :" + fileUri);
            }
        });

        return 0;

    } else {
        try {
            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            URL url = new URL(upLoadServerUri);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", sourceFileUri);


            /* List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("UserId", UserId));

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(params));
            writer.flush();
            writer.close();
            os.close();

            conn.connect();  */

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

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + sourceFileUri + "\"" + lineEnd);

            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) {

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

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(Video.this,
                                "File Upload Complete.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(Video.this,
                            "MalformedURLException", Toast.LENGTH_SHORT)
                            .show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(Video.this,"Something went wrong", Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("UploadingFile Exception","" + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;
    }
}

0 个答案:

没有答案