【问题标题】:Always getting null response when i call an API with city with spaces at openweathermap.com当我在 openweathermap.com 上使用带有空格的城市调用 API 时,总是得到空响应
【发布时间】:2019-07-26 02:54:27
【问题描述】:

当我使用带有空格的城市调用 API 时,我得到一个空响应:例如“旧金山”。例如,当“墨西哥”工作正常时。

我尝试用“+”替换空格,但它在 android 中不起作用。但在邮递员中它起作用了。

这里是调用代码:

Api api = ApiBuilder.createApi();
    Call<CurrentWeather> currentWeatherCall = 
api.getCurrentWeather(API_KEY, "san+francisco", UNITS);

    currentWeatherCall.enqueue(new Callback<CurrentWeather>() {
        @Override
        public void onResponse(Call<CurrentWeather> call, 
Response<CurrentWeather> response) {
            try {
Toast.makeText(getApplicationContext(), response.body().getCityName(),
                        Toast.LENGTH_SHORT).show();
            }

【问题讨论】:

    标签: android retrofit openweathermap


    【解决方案1】:

    如果您使用logging-interceptor,那么您可以在详细日志中看到来自服务器的响应。

    在 Gradle 中 implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'

    在界面中

     public static PostService postService = null;
    
            public static PostService getService() {
            if (postService == null) {
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                OkHttpClient client = new OkHttpClient.Builder()
               .addInterceptor(interceptor).build();
    
                Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(base_url)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
                postService = retrofit.create(PostService.class);
    
            }
            return postService;
            }
    

    如果进行了 api 调用,则可以在 Verbose 中看到服务器响应,然后进行调试

    【讨论】:

    • 谢谢,我使用 okhttp 登录,问题是:我需要加号而不是 URL 中的 252b
    • 你能帮忙吗,我无法将 252b 替换为加号
    • 可以分享一下接口的功能getCurrentWeather()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多