Как в приложении на android отправить http запрос

делаю проект "Умную теплицу", встала проблема управления оной, для чего я решил использовать приложение под android и протокол http для связи с ESP8266 по WiFI. Схема такая: ESP является точкой доступа и сервером, обмениваясь данными с приложением через http заголовки. Первую часть реализовал: ESP заголовки читает, выводит. Тестировал через приложение HTTP Shortcuts из Google Play в режиме curl. Вопрос в том, как заставить мою программу формировать http запросы и отправлять на ESP по заданному IP.

Прилагаю кусок кода на java, но также хочу отметить, что можно и переписать всё на kotlin.

public static void postReq() throws MalformedURLException, IOException {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                URL reqURL = new URL("http://192.168.4.1/"); //the URL we will send the request to
                HttpURLConnection request = (HttpURLConnection) (reqURL.openConnection());
                String post = "this will be the post data that you will send";
                request.setDoOutput(true);
                request.addRequestProperty("Content-Length", Integer.toString(post.length())); //add the content length of the post data
                request.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add the content type of the request, most post data is of this type
                request.setRequestMethod("POST");
                request.connect();
                OutputStreamWriter writer = new OutputStreamWriter(request.getOutputStream()); //we will write our request data here
                writer.write(post);
                writer.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    });
    thread.start();


}

Ответы (0 шт):