N
N
Nikolay Alekseev2019-09-18 18:46:56
Java
Nikolay Alekseev, 2019-09-18 18:46:56

How to send files using HttpUrlConnection?

Good day to all!
I could find very little sensible information on the net, I hope someone can explain something to me.
And so, there is a mobile application, you need to send a file from it to the server where php will receive it.
There are no problems on the php side, but on the client side I don’t understand where the legs grow from.
From those snippets of information and code examples, I was able to assemble and tidy up the following function

static String SendFilePOST(String address, String data, String FilePath) {
        String result = "";
        try {
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1*1024*1024;

            File file = new File(FilePath);
            URL url = new URL(address);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
           //Вот до сюда всё логично
            String boundary = UUID.randomUUID().toString();
           // Что такое boundary и зачем оно нужно? Я понимаю, что это граница, но граница чего? Данных?
            //нужно ли мне это как-то особенным образом обрабатывать на стороне php?
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            DataOutputStream request = new DataOutputStream(conn.getOutputStream());
//если boundary - это граница, то зачем мне тут ещё "--"?
            request.writeBytes("--" + boundary + "\r\n");
            request.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");
            request.writeBytes("Какое-то описание фала\r\n");
            //на сколько я могу судить, здесь я задаю значение переменной description
            //которую смогу прочитать в $_POST['description']
            //Если я понимаю правильно, тогда зачем два переноса строк?
            //и почему дальше я объявляю переменную file, но сразу на ней идёт filename
            //а содержимое файла от его имени отделено только переносами строк?
            request.writeBytes("--" + boundary + "\r\n");
            request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n\r\n");

            //добавление файла
            FileInputStream fileInputStream = new FileInputStream(file);

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

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                request.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            //конец добавления файла

            request.writeBytes("\r\n");

            request.writeBytes("--" + boundary + "--\r\n");
            request.flush();
            int respCode = conn.getResponseCode();

            switch(respCode) {
                case 200:
                    result = "ok";
                    break;
                case 301:
                case 302:
                case 307:
                    //handle redirect - for example, re-post to the new location
                    break;
                default:
                    //do something sensible
            }

        } catch (Exception e) {
            return e.getMessage();
        }
        return result;
    }

I wrote all the main questions in the comments to the code, but there is also a question about receiving a text response from the server, since php responds with a string in json format after accepting the file.
Perhaps I chose not the easiest way and you can do it somehow differently, I will be overly grateful for the hint.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
UserTwo, 2019-09-18
@VariusRain

Of course, I'm not a professional, but I would advise you to use one of the popular libraries for such purposes and in general for http requests, for example OkHttp https://square.github.io/okhttp/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question