在Android中使用HTTPURLConnection发送文件和参数

时间:2018-03-16 04:45:22

标签: php android httpurlconnection

我目前正在使用Android中的HTTPURLConnection类将一些图像发送到我的php服务器。 图像传输运行正常,但主要问题是我也需要发送一个参数(如数字,例如:2)。我真的不知道该怎么做。 当我传输参数时,如何获取它并在我的php服务器中使用它?

这是我的代码:

        URL url = new URL(url_path);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setChunkedStreamingMode(1024);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data");

        OutputStream outputStream = conn.getOutputStream();
        InputStream inputStream = c.getContentResolver().openInputStream(path);

        int bytesAvailable = inputStream.available();
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];

        int bytesRead;
        while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) != -1) {
            outputStream.write(buffer, 0, bytesRead); //Sending the image
            //Here is where I need the parameter to be sent too.

        }
        outputStream.flush();
        inputStream.close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            Log.i("result", line);
        }
        reader.close();
        conn.disconnect();

这是我的PHP代码,非常简单:

<?php
    $file_name = date("U").".jpg"; //I'm going to use the parameter here
    $server_path = "uploads/";
    $web_path = "http://xxxxxxxxxxxxxxxxxxxxxxx/";
    $file = $server_path.$file_name;
    file_put_contents($file,"");


    $fp = fopen("php://input", 'r');
    while ($buffer =  fread($fp, 8192)) {
        file_put_contents($file,$buffer,FILE_APPEND | LOCK_EX);
    }
    echo $web_path.$file_name;
   ?>

非常感谢!

0 个答案:

没有答案