dongtiao2066 2018-06-28 09:33 采纳率: 0%
浏览 173

通过HttpURLConnection POST Android将变量传递给PHP

I have funcation to upload pdf file using HttpURLConnection , it's work and the pdf file is uploaded , now i want to pass variables UserID , ProviderId and so on , i tried this way as the code below but i dont know why its not working , the pdf file is uploaded but nothing enter to the database

the Part i add the variables

                connection.setRequestProperty("USERID",UserId); // 
                connection.setRequestProperty("ProviderID",DriverIDFinal);
                connection.setRequestProperty("belongto","USER"); // 
                connection.setRequestProperty("paidstatus","0"); // 
                connection.setRequestProperty("pdffileurl",PdfUrlServer); //

this is my code

public int uploadFile(final String selectedFilePath){



        int serverResponseCode = 0;

        HttpURLConnection connection;
        DataOutputStream dataOutputStream;
        String lineEnd = "
";
        String twoHyphens = "--";
        String boundary = "*****";


        int bytesRead,bytesAvailable,bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File selectedFile = new File(selectedFilePath);


        String[] parts = selectedFilePath.split("/");
        final String fileName = parts[parts.length-1];

        PdfUrlServer = "http://*****/****/pdfrec/"+ fileName;

        if (!selectedFile.isFile()){
            hideDialog();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(****.this,"Source File Doesn't Exist",Toast.LENGTH_SHORT).show();
                }
            });
            return 0;
        }else{
            try{
                FileInputStream fileInputStream = new FileInputStream(selectedFile);
                URL url = new URL(SERVER_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);//Allow Inputs
                connection.setDoOutput(true);//Allow Outputs
                connection.setUseCaches(false);//Don't use a cached Copy
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("ENCTYPE", "multipart/form-data");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                connection.setRequestProperty("uploaded_file",selectedFilePath);
                connection.setRequestProperty("USERID",UserId); // here is where i add the par....
                connection.setRequestProperty("ProviderID",DriverIDFinal);
                connection.setRequestProperty("belongto","USER"); // 
                connection.setRequestProperty("paidstatus","0"); // 
                connection.setRequestProperty("pdffileurl",PdfUrlServer); // 



                //creating new dataoutputstream
                dataOutputStream = new DataOutputStream(connection.getOutputStream());

                //writing bytes to data outputstream
                dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
                dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + selectedFilePath + "\"" + lineEnd);

                dataOutputStream.writeBytes(lineEnd);

                //returns no. of bytes present in fileInputStream
                bytesAvailable = fileInputStream.available();
                //selecting the buffer size as minimum of available bytes or 1 MB
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                //setting the buffer as byte array of size of bufferSize
                buffer = new byte[bufferSize];

                //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
                bytesRead = fileInputStream.read(buffer,0,bufferSize);

                //loop repeats till bytesRead = -1, i.e., no bytes are left to read
                while (bytesRead > 0){
                    //write the bytes read from inputstream
                    dataOutputStream.write(buffer,0,bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable,maxBufferSize);
                    bytesRead = fileInputStream.read(buffer,0,bufferSize);
                }

                dataOutputStream.writeBytes(lineEnd);
                dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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

                Log.i("TAG", "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);

                //response code of 200 indicates the server status OK
                if(serverResponseCode == 200){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //add the code after the pdf is uploaded


                        }
                    });
                }

                //closing the input and output streams
                fileInputStream.close();
                dataOutputStream.flush();
                dataOutputStream.close();



            } catch (FileNotFoundException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(****.this,"File Not Found",Toast.LENGTH_SHORT).show();


                    }
                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
                Toast.makeText(****.this, "URL error!", Toast.LENGTH_SHORT).show();

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(****.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
            }
            hideDialog();
            return serverResponseCode;
        }

    }

and this is my PHP

<?php

    include 'include/DatabaseConfig.php';

// Create connection
    $conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);



    $file_path = "pdfrec/";
    $UserID = $_POST['USERID'];
    $ProviderID = $_POST['ProviderID'];
    $belongto = $_POST['belongto'];
    $paidstatus = $_POST['paidstatus'];
    $pdffileurl = $_POST['pdffileurl'];

    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){

        $InsertSQL = "INSERT INTO **** (userid, providerid, belongto, paidstatus, pdffileurl) VALUES ($UserID,$ProviderID,$belongto,$paidstatus,$pdffileurl)";

        if(mysqli_query($conn, $InsertSQL)){


        }

        mysqli_close($conn);
        echo "success";
    } else{
        echo "fail";
    }
 ?>
  • 写回答

1条回答 默认 最新

  • dqgg25493 2018-06-28 09:36
    关注

    The setRequestProperty sets headers. POST data is in the body of the request.

    See this question on how to do that:

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("USERID", UserId));
    ... add others ...
    OutputStream os = connection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();
    
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP