1
I can make an HTTPS request normally in an app, but it doesn’t work when it’s HTTP. You would have to configure something in Android Studio to be able to make the HTTP request?
The code of my class responsible for the request is below. I am using Android Studio 3.4.2
Loaded.java ( Httpservice )
package com.projetos.conexaoapi;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class CarregaDados extends AsyncTask<Void, Void, Void>{
String dados = "";
private final String urlParam;
public CarregaDados(String urlParam) {
this.urlParam = urlParam;
}
@Override
protected Void doInBackground(Void... voids) {
try {
//URL url = new URL("https://brasilapi.com.br/api/feriados/v1/2021");
//URL url = new URL("https://viacep.com.br/ws/01001000/json");
URL url = new URL(urlParam);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null){
line = bufferedReader.readLine();
dados = dados + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.twDados.setText(this.dados);
}
}
Thanks for the personal feedback, I will test here, then comment with was... the Detail is that I am connecting to an Internal Network, a REST API ( Spring Boot ), and by default the Request is http, in a Browse the return works normal, in Postman also works, in a Reactjs application also, but on Android had this detail, it took me a while to realize that the detail was due to the type of http connection that was going, as mentioned.
– José Aparecido
It worked by putting this line on Androidmanifest ( android:usesCleartextTraffic="true" ), then putting the authorizations according to the urls you use. Thank you very much, thank you very much!
– José Aparecido
@Don’t forget to give vote +1 if this answer was useful to you. And also to mark it as a favorite if you judge it as the best solution. Analyze the other answer as well and give feedback. So you help other devs who have the same problem to find and better solution.
– Cmte Cardeal
Hello, when I try to vote, because I post little thing around here, it doesn’t validate... I usually solve what I need to see other posts on the subject, I’ll see how to improve it... thanks!
– José Aparecido
@Just like you can’t vote because of your reputation, but you can still accept the answer, it will mark your question as solved. Read more on How and why to accept an answer?
– Rafael Tavares