Android Studio利用阿里云获得天气数据


📋 作者介绍:友友们好我是乱披风锤,大二学生党一枚
💖作者主页:乱披风锤的个人博客主页.跳转到个人简介
🔥我和友友们一样喜欢编辑,天天敲代码🤭,沉迷学习,日渐消瘦。很荣幸能向大家分享我的所学,和大家一起进步。如果文章有错误,欢迎在评论区指正。那么开始今天的学习吧!
🎉 支持我:点赞👍+收藏⭐️+留言📝


一、准备工作,开启网络访问权限

AndroidManifest.xml加入

   <uses-permission android:name="android.permission.INTERNET"/>
 android:usesCleartextTraffic="true"


二、导包,添加依赖

在这里插入图片描述

 implementation 'com.google.code.gson:gson:2.9.0'
    implementation("com.squareup.okhttp3:okhttp:4.9.3")

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

    implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'

三、打开阿里云服务,注册加上实名认证,购买使用次数,有100次优惠,我们买那个就好了

在这里插入图片描述

找到APPCODE复制下来
在这里插入图片描述

放入Android Studio中如图所示位置,需要注意的是APPCODE后面必须加空格
在这里插入图片描述

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.textView);
        String  code="APPCODE "+"de60f45d0a04479f8c3eb458e87663d3";

四、建立一个Api接口实现它

package com.hnucm.network2;


import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Query;
//de60f45d0a04479f8c3eb458e87663d3
//http://121.4.44.56/object1
public interface Api {
    @GET("object")
    Call<Student> getStudent();

    @GET("area-to-weather")
    Call<WeatherResult> getWeather(@Header("Authorization") String code, @Query("area")String area);


}


五、核心代码

package com.hnucm.network2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.DownloadManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.textView);
        String  code="APPCODE "+"de60f45d0a04479f8c3eb458e87663d3";



//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl("http://121.4.44.56/ ")
//                .addConverterFactory(GsonConverterFactory.create())
//                .build();
        Api api=RetrofitUtils.getRetrofit("http://ali-weather.showapi.com/").create(Api.class);


        Call<WeatherResult> studentCall=api.getWeather(code,"长沙");
        studentCall.enqueue(new Callback<WeatherResult>() {
            @Override
            public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                //请求成功  主线程
                WeatherResult weatherResult=response.body();
                //文本控件不能给整数值    只能给字符串
               // textView.setText(student.age+" ");
                textView.setText(weatherResult.showapiResBody.now.temperature);
            }

            @Override
            public void onFailure(Call<WeatherResult> call, Throwable t) {

            }

            });

//        OkHttpClient okHttpClient=new OkHttpClient();
//       Request request=new Request
//               .Builder()
//               .url("https://www.fastmock.site/mock/e311152213834d9887108e10e5719090/getstudent/getstudent")
//               .get().build();
//        Call call=okHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(@NonNull Call call, @NonNull IOException e) {
请求失败时
//            }
//
//            @Override
//            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//               // Log.i("OKHttpClient",response.body().string());
//                String result=response.body().string();
//                Log.i("OKHttpClient",result);
//                Gson gson=new Gson();
//                Student student=gson.fromJson(result,Student.class);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        textView.setText(student.name);
//                    }
//                });
//
//            }
//        });
    }
}

六、实现效果

这里我获取的是长沙现在的温度,小伙伴们可以根据自己需要的数据进行调整

  public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                //请求成功  主线程
                WeatherResult weatherResult=response.body();
                //文本控件不能给整数值    只能给字符串
               // textView.setText(student.age+" ");
                textView.setText(weatherResult.showapiResBody.now.temperature);
            }


在这里插入图片描述

总结

好了,那么今天的学习就到这里了。友友们觉得不错的可以给个关注,点赞或者收藏哦!感谢各位友友们的支持。以下的代码希望各位大佬们自行检验哦,毕竟亲手操作让记忆更加深刻。

  • 23
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值