Note! Android does not allow you to make http requests in the main stream.
Decision: Therefore
in Java code, we create a regular additional thread. Let's read more about Thread ...
Java
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override public void run() {
...
}
});
In the
MyUtils.java file, I made the
SendHttpRequest method to send any http (web api) request
Java
File 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) I send an http (web api) request to
https://dir.by/developer2) I get a response as html text
3) in the main stream we will find TextView by id
4) I set the text
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);
});
});
All code:
Java
File 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);
});
});
}
}