Ответ сервера: Неверный запрос: 400 в httpurlconnection - PullRequest
0 голосов
/ 05 июля 2019

public int uploadFile (final String selectedFilePath) {

    int serverResponseCode = 0;

    HttpURLConnection connection;
    DataOutputStream dataOutputStream;
    String lineEnd = "\r\n";
    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];

    if (!selectedFile.isFile()){
       // dialog.dismiss();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
            }
        });
        return 0;
    }else{
        try{
            String sno = String.valueOf(439);
            String topic_id = String.valueOf(172);
            FileInputStream fileInputStream = new FileInputStream(selectedFile);
            URL url = new URL(SERVER_URL);
            connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Accept","application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);


            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();



            JSONObject jsonObjectPost1 = new JSONObject();
            jsonObjectPost1.put("sno", sno);
            jsonObjectPost1.put("topic_id", topic_id);
            jsonObjectPost1.put("attach_files", selectedFilePath);

            jsonArray.put(jsonObjectPost1);
            jsonObject.put("data", jsonArray);

            //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(connection.toString());

            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);
            dataOutputStream.writeBytes(connection.toString());

            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() {
                        tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://coderefer.com/extras/uploads/"+ fileName);
                    }
                });
            }

            //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(MainActivity.this,"File Not Found",Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "URL error!", Toast.LENGTH_SHORT).show();

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

}

цель: - загрузить все типы файлов на сервер, у меня есть попытка, но ничего не работает, мой объект json

{
    "m_insert_status": true,
    "data": [
      {
        "message_text": "vdJ1pMc6XI7Kg1IaUwUScAzID/LqFYK9DwtxtYgnO3FDErd+iWgud2OPy7iDqGjgykJQdAgVHhUeCfAlzvJt5g==",
        "message_link": "https://hgedgdgwh",
        "userid": "165",
        "topic_id": "172",
        "reply_user_id": "0",
        "reply_message_id": "0"
      }
    ],
    "message": "Topic Insert Successfully"
}

Ответы [ 3 ]

0 голосов
/ 05 июля 2019

Я предлагаю использовать несколько полезных библиотек, Модернизация решит большинство ваших проблем или используйте OkHttp , если вы хотите получить ответ на необработанные данные

0 голосов
/ 05 июля 2019

неверный запрос: 400, обычная причина - отправка неправильных данных, таких как неправильные имена или типы полей

0 голосов
/ 05 июля 2019

Попробуйте изменить

HttpURLConnection connection;

на

HttpsURLConnection connection;

В документе по настройке безопасности сети Google вы можете исправить это, добавивэто -

<?xml version="1.0" encoding="utf-8"?>
    <manifest ...>
       ...
       <application
          ...
          android:usesClearTextTraffic="true"
          ...>
       ...
       </application>
   </manifest>  

К вашему файлу AndroidManifest.xml

Для получения дополнительной информации вы можете проверить документ Google, поэтому Конфигурация сетевой безопасности здесь - "https://developer.android.com/training/articles/security-config"

...