2

Я пытаюсь получить данные о погоде.

Мой BASE_URL:

api.openweathermap.org/data/2.5/weather?q=Makhachkala,RU/main&APPID=0b08836a21c5d5280dbc3e634a3712a7

Получаю ошибку:

java.lang.IllegalArgumentException: Illegal URL: api.openweathermap.org/

NetworkRequest

public class NetworkRequest {
    private static NetworkRequest request;
    private static final String BASE_URL = "api.openweathermap.org/";
    private Retrofit retrofit;

    NetworkRequest() {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static NetworkRequest getRequest(){
        if(request == null){
            request = new NetworkRequest();
        }
        return request;
    }

    public WeatherAPI getWeatherApi(){
        return  retrofit.create(WeatherAPI.class);
    }
}

Интерфейс

public interface WeatherAPI {
    @GET ("data/2.5/weather?id=532096")
    Call<Weather> getWeather();
}

Класс Weather

public class Weather {
    @SerializedName("name")
    @Expose
    private String locale;

    @SerializedName("temp")
    @Expose
    private String temperature;

    @SerializedName("description")
    @Expose
    private String description;

    @SerializedName("humidity")
    @Expose
    private String humidity;

    public String getLocale() {
        return locale;
    }
    public void setLocale(String locale) {
        this.locale = locale;
    }

    public String getTemperature() {
        return temperature;
    }
    public void setTemperature(String temperature) {
        this.temperature = temperature;
    }

    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

    public String getHumidity() {
        return humidity;
    }
    public void setHumidity(String humidity) {
        this.humidity = humidity;
    }
}

И MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView tvLocation = findViewById(R.id.tv_location);
    final TextView tvTemperature = findViewById(R.id.tv_temperature);
    final TextView tvDescription = findViewById(R.id.tv_description);
    final TextView tvHumidity = findViewById(R.id.tv_humidity);


    NetworkRequest networkRequest = new NetworkRequest();
    networkRequest.getRequest()
            .getWeatherApi()
            .getWeather()
            .enqueue(new Callback<Weather>() {
                @Override
                public void onResponse(Call<Weather> call, Response<Weather> response) {
                    Weather weather = response.body();

                    tvLocation.append(weather.getLocale());
                    tvDescription.append(weather.getDescription());
                    tvTemperature.append(weather.getTemperature());
                    tvHumidity.append(weather.getHumidity());
                }

                @Override
                public void onFailure(Call<Weather> call, Throwable t) {
                    Toast.makeText(MainActivity.this, "Не удалось", Toast.LENGTH_LONG).show();
                }
            });

}

Ошибка

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.idrisov.weather, PID: 8336
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.idrisov.weather/com.idrisov.weather.MainActivity}: java.lang.IllegalArgumentException: Illegal URL: api.openweathermap.org/
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
 Caused by: java.lang.IllegalArgumentException: Illegal URL: api.openweathermap.org/
    at retrofit2.Retrofit$Builder.baseUrl(Retrofit.java:456)
    at com.idrisov.weather.NetworkRequest.<init>(NetworkRequest.java:13)
    at com.idrisov.weather.MainActivity.onCreate(MainActivity.java:26)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
0

3 ответа 3

3

Корректным будет адрес

http://api.openweathermap.org/

Либо

https://api.openweathermap.org/

Это легко забыть:)

1
  • спасибо). Сколько раз запускал, даже не взглянул на начало адреса). Теперь другая ошибка вышла)) 11 мая 2020 в 19:48
3

Вы не добавили протокол к вашей базовой ссылке http:// или https://

Таким образом корректной будет ссылка:

http://api.openweathermap.org/data/2.5/......

Или:

https://api.openweathermap.org/data/2.5/......
0

Помимо правильного URL вы еще не добавили параметр APPID в конструктор

 public interface WeatherAPI {
    @GET ("data/2.5/weather?id=532096")
    Call<Weather> getWeather(@Query("APPID") appId: String);
}

тогда при вызове нужно его передать

public static final String KEY_WEATHER = "0b08836a21c5d5280dbc3e634a3712a7";

NetworkRequest networkRequest = new NetworkRequest();
networkRequest.getRequest()
        .getWeatherApi()
        .getWeather(KEY_WEATHER)..............

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.