На заметку! Андроид не позволяет выполнять http запросы в главном потоке.
Решение: Поэтому
В коде Java мы создаём обычный дополнительный поток. Давайте почитаем подробнее о Thread ...
Java
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override public void run() {
...
}
});
В файле
MyUtils.java сделал метод
SendHttpRequest для отправки любого http (web api) запроса
Java
Файл MyUtils.java
package com.example.androidapp1;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class MyUtils {
public static void SendHttpRequest(String httpPath, String method, String requestType, Consumer<String> myMethodWhenHttpFinished)
{
// create my thread
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override public void run() {
try {
URL url = new URI(httpPath).toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Accept", requestType);
connection.setRequestProperty("Content-Type", requestType);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String htmlOrJson = reader.lines().collect(Collectors.joining("\n"));
myMethodWhenHttpFinished.accept(htmlOrJson);
}
}
catch (Exception e) {
myMethodWhenHttpFinished.accept(null);
}
}
});
}
}
1) Отправляю http (web api) запрос на
https://dir.by/developer
2) получаю ответ как html текст
3) в главном потоке найдем TextView по id
4) устанавливаю текст
Java
MyUtils.SendHttpRequest("https://dir.by/developer",
"GET",
"application/html",
(httpResponse) -> {
// main thread
new Handler(Looper.getMainLooper()).post(() -> {
// set text
TextView myElement = this.findViewById(R.id.my_element1);
if (myElement!=null)
myElement.setText(httpResponse);
});
});
Весь код:
Java
Файл MainActivity.java
package com.example.androidapp1;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// send http
MyUtils.SendHttpRequest("https://dir.by/developer",
"GET",
"application/html",
(httpResponse) -> {
// main thread
new Handler(Looper.getMainLooper()).post(() -> {
// set text
TextView myElement = this.findViewById(R.id.my_element1);
if (myElement!=null)
myElement.setText(httpResponse);
});
});
}
}