Android network programming (2) - brief record of the use of retrofit

osc_ u1w6ntu7 2021-01-21 10:21:59
android network programming brief record


Android Network programming ( Two )

First time to know Retrofit Network framework , Make a brief note of the usage process :

I understand. Retrofit

Retrofit Network framework , In essence, it's just what I've introduced before OkHttp frame ,Retrofit It's a layer of encapsulation , Configure network request parameters through annotations , Support synchronous and asynchronous , And there's a way to directly UI Thread update interface ;

Retrofit Usage flow

1. First, add Retrofit Dependent dependency ;
2. according to API Or the network requests the returned data to establish a data analysis class , What we use here is GSON analysis ;
3. establish Retrofit Interface for making network requests ;
4. newly build Retrofit example , Pass in the parameter ;
5. Instantiation interface , use Retrofit The example goes on create();
6. Instantiation Call<>, Configure network request parameters ;
7. Send network request ;





OVER!!!OVER!!!


Let's do it step by step :

1. Add dependencies :

 //Retrofit library 
compile 'com.squareup.retrofit2:retrofit:2.0.2'
//OkHttp library 
compile 'com.squareup.okhttp3:okhttp:3.1.2'
//Retrofit Corresponding version Gson library 
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

2. Create receive data instance class :

It was introduced before GSONFormat Automatically create data classes , I won't introduce it here , If you are interested, you can have a look at , Pretty simple , Just skip over here , Our data parsing class is called Weather, I'll use it next ;


3. Create a network request interface :

stay Retrofit in , This part is a very important part , We used annotations ,Retrofit There are a lot of notes in the text , Now I use @GET as well as @POST, Most of the problems can be solved .

1).@GET:

@GET() In parentheses , What's written is part of url website , Because public url We will set it when we use it , The suffixes are different , The return parameters are different , So in GET() Different parts will be written in :

 @GET("?")

This is what I use API The uncertain part of :

https://query.asilu.com/weather/baidu/?city= nanjing 

This is it. API The website of , We can send in cities to get data , The front is the same , So all we have to do is GET writes “?” Can , So how do we pass in this parameter :

Call<Weather> getWeather(@Query("city") String city);

This Weather This is the data parsing class mentioned before ,@Query This part represents a key value pair , My understanding is that , The key value pairs written in this place will do “city = city” Such a situation is placed in ? The back as a whole url Pass in , If there's something wrong, I hope you can tell me ;

2). @POST

seeing the name of a thing one thinks of its function , This requires us to upload some data , For example, when we upload data, log in and register , That's what you need , It's easy to use now , For a brief record :

 @POST("?")
@FormUrlEncoded
Call<Weather> getCity(@Field("city") String city);

@FormUrlEncoded The purpose of this note is to show that the upload is in the form of a form , Below @Field In my understanding and before @Query The meaning is the same , It's just an act of URL website , One as data ;


4. Instantiation Retrofit:

Let's start with the code :

String url="https://query.asilu.com/weather/baidu/";
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();

Simple code , New Retrofit.Builder(), Then incoming baseUrl() We set it up url value , Then set up to use Gson analysis , Last build() once ;


5. According to the just instantiated retrofir Instantiate the network request interface :

WeatherInter weatherInter = retrofit.create(WeatherInter.class);

That's it ;


6. Instantiation Call, Configure network request parameters :

Call<Weather> call=weatherInter.getCity(city);

Let's test here to get the weather of the city we want , So set up getCity();


7. Send network request :

 call.enqueue(new Callback<Weather>() {

@Override
public void onResponse(Call<Weather> call, Response<Weather> response) {

String weather=response.body().getCity();
textView.setText(weather);
}
@Override
public void onFailure(Call<Weather> call, Throwable t) {

Toast.makeText(RetrofitActivity.this, "???", Toast.LENGTH_SHORT).show();
}
});

OVER!!!OVER!!!

It's easier to use than the others , But there are other things that need to be studied , Next, paste the whole code :

public interface WeatherInter {

@GET("?")
Call<Weather> getWeather(@Query("city") String city);
@POST("?")
@FormUrlEncoded
Call<Weather> getCity(@Field("city") String city);
}
public class RetrofitActivity extends AppCompatActivity {

private ImageView imageView;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrofit);
imageView=findViewById(R.id.retrofit_Go);
textView=findViewById(R.id.retrofit_Text);
imageView.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

Retrofit(" Jining ");
}
});
}
public void retrofit(){

String url="https://query.asilu.com/weather/baidu/";
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherInter weatherInter=retrofit.create(WeatherInter.class);
Call<Weather> call=weatherInter.getWeather(" Jining ");
call.enqueue(new Callback<Weather>() {

@Override
public void onResponse(Call<Weather> call, Response<Weather> response) {

String weather=response.body().getWeather().get(0).getWeather();
textView.setText(weather);
}
@Override
public void onFailure(Call<Weather> call, Throwable t) {

Toast.makeText(getApplicationContext(),"???",Toast.LENGTH_SHORT).show();
}
});
}
public void Retrofit(String city){

String url="https://query.asilu.com/weather/baidu/";
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherInter weatherInter=retrofit.create(WeatherInter.class);
Call<Weather> call=weatherInter.getCity(city);
call.enqueue(new Callback<Weather>() {

@Override
public void onResponse(Call<Weather> call, Response<Weather> response) {

String weather=response.body().getCity();
textView.setText(weather);
}
@Override
public void onFailure(Call<Weather> call, Throwable t) {

Toast.makeText(RetrofitActivity.this, "???", Toast.LENGTH_SHORT).show();
}
});
}
}

There's nothing to post , But I just want to see more , That's it .

 Insert picture description here

版权声明
本文为[osc_ u1w6ntu7]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121101717239n.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云