Android HttpURLConnection可发送带有参数may(字符串或Json字符串)的图像、音频和视频文件

Android HttpURLConnection可发送带有参数may(字符串或Json字符串)的图像、音频和视频文件,android,httpurlconnection,Android,Httpurlconnection,我正在使用HttpURLConnection共享解决方案以发送带有参数的图像、音频或视频文件。参数可以是(纯字符串或JSON) (Android客户端到PHP后端) 情景: 必须上传媒体文件(带参数的音频、视频和图像) 媒体文件将存储在服务器文件夹中,并将参数保存到数据库中 我遇到了一个问题,图像成功上传,而参数丢失 潜在解决方案 选择HttpURLConnection而不是Httpclient作为 你可能想知道,哪个客户是最好的 ApacheHTTP客户端在Eclair和Froyo上的bug较

我正在使用HttpURLConnection共享解决方案以发送带有参数的图像音频视频文件。参数可以是(纯字符串或JSON)

(Android客户端到PHP后端)

情景: 必须上传媒体文件(带参数的音频、视频和图像)

媒体文件将存储在服务器文件夹中,并将参数保存到数据库中

我遇到了一个问题,图像成功上传,而参数丢失

潜在解决方案

选择HttpURLConnection而不是Httpclient作为

你可能想知道,哪个客户是最好的

ApacheHTTP客户端在Eclair和Froyo上的bug较少。这是这些版本的最佳选择

对于姜饼和更好的产品,HttpURLConnection是最佳选择。其简单的API和小尺寸使其非常适合Android。透明压缩和响应缓存减少了网络使用,提高了速度并节省了电池。新应用程序应使用HttpURLConnection;这是我们将花费精力前进的地方

Android代码:

public int uploadFile(final String sourceFileUri) {

    String fileName = sourceFileUri;

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

    if (!sourceFile.isFile()) {

        dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :" + filepath);

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :" + filepath);
            }
        });

        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", fileName);


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


            dos.writeBytes(twoHyphens + boundary + lineEnd);

//Adding Parameter name

            String name="amir";
            dos.writeBytes("Content-Disposition: form-data; name=\"name\"" + lineEnd); 
            //dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
            //dos.writeBytes("Content-Length: " + name.length() + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(name); // mobile_no is String variable
            dos.writeBytes(lineEnd);

            dos.writeBytes(twoHyphens + boundary + lineEnd);

//Adding Parameter phone
            String phone="9956565656";
            dos.writeBytes("Content-Disposition: form-data; name=\"phone\"" + lineEnd); 
            //dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
            //dos.writeBytes("Content-Length: " + name.length() + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(phone); // mobile_no is String variable
            dos.writeBytes(lineEnd);


            //Json_Encoder encode=new Json_Encoder();
            //call to encode method and assigning response data to variable 'data'
            //String data=encode.encod_to_json();
            //response of encoded data
            //System.out.println(data);


                //Adding Parameter filepath

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            String filepath="http://192.168.1.110/echo/uploads"+fileName;

            dos.writeBytes("Content-Disposition: form-data; name=\"filepath\"" + lineEnd); 
            //dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
            //dos.writeBytes("Content-Length: " + name.length() + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(filepath); // mobile_no is String variable
            dos.writeBytes(lineEnd);


//Adding Parameter media file(audio,video and image)

            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + 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);


            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();



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

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {
                         msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                + "c:/wamp/www/echo/uploads";
                        messageText.setText(msg);
                        Toast.makeText(MainActivity.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() {
                    messageText
                            .setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(MainActivity.this,
                            "MalformedURLException", Toast.LENGTH_SHORT)
                            .show();
                }
            });

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

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

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Got Exception : "+e.toString());
                    Toast.makeText(MainActivity.this,
                            "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;
    }
}
Php代码:

$file_path = "uploads/";

//receive parameters

  $name=$_POST['name'];
  $phone=$_POST['phone'];
  $filepath=$_POST['filepath'];


   //receive media files(image , audio and video)

   $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
   if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) 
      {
      echo "Success";
      }
希望这有帮助


任何疑问都可以问我。

您可以使用API调用。对Android的最低支持是2.3。请查看详细信息。

您可以让它更简单!尝试以下方法

public static String uploadImage(Bitmap bitmap, String urlString) {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap = Local.resize(bitmap, 512, 512);
        if(filename.toLowerCase().endsWith("jpg") || filename.toLowerCase().endsWith("jpeg"))
            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, bos);
        if(filename.toLowerCase().endsWith("png"))
            bitmap.compress(Bitmap.CompressFormat.PNG, 70, bos);
        ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), filename);
        ContentBody body1 = new StringBody("something");
        ContentBody body2 = new StringBody("something");
        org.apache.http.entity.mime.MultipartEntity reqEntity = new org.apache.http.entity.mime.MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("image", contentPart);
        reqEntity.addPart("sample1", body1);
        reqEntity.addPart("sample2", body2);
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
        conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
        OutputStream os = conn.getOutputStream();
        reqEntity.writeTo(conn.getOutputStream());
        os.close();
        conn.connect();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            Log.d("UPLOAD", "HTTP 200 OK.");
            return readStream(conn.getInputStream());
            //This return returns the response from the upload.
        } else {
            Log.d("UPLOAD", "HTTP "+conn.getResponseCode()+" "+conn.getResponseMessage()+".");
            String stream =  readStream(conn.getInputStream());
            //Log.d("UPLOAD", "Response: "+stream);
            return stream;
        }
    } catch (Exception e) {
        Log.d("UPLOAD_ERROR", "Multipart POST Error: " + e + "(" + urlString + ")");
    }
    return null;
}

您是否能够通过图像或视频获取其他变量?请在此解释
conn
变量,您尚未调用
connect
操作,您如何期望有响应代码?问答网站也是如此。请将您的帖子添加到您留下的问题中,并在下面发布一个答案。实际上,devs使用OKHTTP/reformation来完成这些任务。甚至谷歌也不使用Apache客户端/HttpURLConnection,而是使用OKHTTP。看看PlayMarket应用程序,以确保在较新的Android版本(4.4+)中.HttpURLConnection由okhttp(而不是Apache)支持。