Не могу сделать http запрос в Android
У меня не получается сделать http запрос в Android, код ниже; В манифесте разрешение есть
public class WebRequests {
public String getContent(String http) throws IOException {
HttpURLConnection connection = null;
String line = null;
try {
connection = (HttpURLConnection) new URL(http).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setConnectTimeout(250);
connection.setReadTimeout(250);
connection.connect();
StringBuilder sb = new StringBuilder();
if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = in.readLine()) != null) {
sb.append(line);
}
Log.d("WebReqeust", line);
} else {
Log.e("WebRequest", connection.getResponseCode() + ", " + connection.getResponseMessage());
}
} catch (Throwable cause) {
cause.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return line;
}
}
Ответы (1 шт):
Автор решения: Arty Morris
→ Ссылка
Вот код запроса погоды
public static JSONObject getWeatherJSON(String lat, String lon){
String _input = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon;
URL url = null;
try {
url = new URL(_input);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder json = new StringBuilder(1024);
String tmp="";
while(true) {
try {
if ((tmp = reader.readLine()) == null) break;
} catch (IOException e) {
e.printStackTrace();
}
json.append(tmp).append("\n");
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject data = null;
try {
data = new JSONObject(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
// This value will be 404 if the request was not
// successful
try {
if (data.getInt("cod") != 200){
return null;
}
} catch (JSONException e) {
e.printStackTrace();
}
return data;
}
плюсом в манифесте прописать
android:usesCleartextTraffic="true"