当前位置:网站首页>Network request -volley
Network request -volley
2022-06-25 00:25:00 【lcj908692】
Volley Is the use and interface
Say something else : about callback Concept and significance of . Wikipedia explains this : Pass a piece of code as a parameter , And this code will be run at some point ;
Personal understanding is : To keep the code clean . To make it easier to call and run something that is not in the same java Variables and functions in the file ; In order to make it easy to set aside an interface , It is convenient to add new functions later ;
/**
- Let's first introduce the functions of the three classes :
- Volley.java:Volley The main category of external exposure , adopt newRequestQueue(…) Function to create and start a request queue RequestQueue.
- Request: Requested abstract class .StringRequest、JsonRequest、ImageRequest It's all its subclasses , Represents a type of request . High scalability .
- RequestQueue.java: Request queue , It contains a CacheDispatcher( The scheduling thread used to process the cache request )、
NetworkDispatcher Array ( Scheduling thread used to process network requests ), One ResponseDelivery( Returns the result distribution interface ),
adopt start() When the function starts, it starts CacheDispatcher and NetworkDispatchers. - Then look back Volley The architecture of the figure .
- First step : Add the request to the cache queue
- The second step :「 Cache scheduling thread 」CacheDispatcher Take a request from the cache queue , If cache hits , Just read the cached response and parse , Then return the result to the main thread
- The third step : Cache miss , The request is added to the network request queue ,「 Network scheduling thread 」NetworkDispatcher Poll fetch request ,HTTP Request transmission , Parse response , Write cache , Then return the result to the main thread
*/
give an example :
public class MainActivity extends AppCompatActivity {
private static final String TAG = “lcj MainActivity”;
TextView requestNetTv;
TextView showNetContentTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
requestNetTv = findViewById(R.id.request_net);
showNetContentTv = findViewById(R.id.show_net_content);
requestNetTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// requestNet();
VolleyHttpUtils.requestNet(
“https://www.baidu.com”,
MainActivity.this,
new VolleyHttpUtils.OnHttpListener() { // Set listening
@Override
public void onResponse(String response) {
Log.i(TAG, “onResponse response:” + response);
Log.i(TAG, “onResponse threadName:” + Thread.currentThread().getName());
showNetContentTv.setText(response);
}
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, “onErrorResponse error:” + error.getMessage());
}
}
);
}
});
}
private void requestNet() {
// First step , utilize Volley new Come up with a request queue
RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);
// The second step , Create a request
// ad locum , What we need to care about is whether the request is a success or a failure . Just these two points . It can be encapsulated with interfaces .
StringRequest stringRequest = new StringRequest(
“https://www.baidu.com”, // request url
new Response.Listener() { // Listening that returns the correct result
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, “ Successful visit ”, Toast.LENGTH_SHORT).show();
showNetContentTv.setText(response);
}
},
new Response.ErrorListener() { // Listening to return error results
@Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, “onErrorResponse error:” + error.getMessage());
}
});
// The third step , Put the request in the queue
mQueue.add(stringRequest);
}
}
public class VolleyHttpUtils {
private static final String TAG = “lcj VolleyHttpUtils”;
// In addition to the introduction of the necessary url And out of context , The key is to implement our interface , In this way, the outside world can easily explain the work to us
// We can't write things to death , You need to give the caller some freedom , What exactly does he want? Let him do it himself , Then the real work is still on our own
public static void requestNet(String url, Context context, final OnHttpListener onHttpListener) {
// First step : Create a queue
RequestQueue mQueue = Volley.newRequestQueue(context);
Log.i(TAG, “requestNet threadName:” + Thread.currentThread().getName());
// The second step : Create request object
StringRequest stringRequest = new StringRequest(url,
new Response.Listener() {
@Override
public void onResponse(String response) {
Log.i(TAG, “requestNet 2 threadName:” + Thread.currentThread().getName());
// The successful code of the external implementation interface about the request is actually executed here
onHttpListener.onResponse(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// The external implementation interface tells the code about the failure of the request, which is actually executed here
onHttpListener.onErrorResponse(error);
}
});
// The third step : Add the request queue to the request queue
mQueue.add(stringRequest);
}
interface OnHttpListener {
void onResponse(String response);
void onErrorResponse(VolleyError error);
}
}
Print the results :
边栏推荐
- Some examples of MgO operating database in go
- Encryption and encoding resolution
- VNC viewer remote connection raspberry pie without display
- Alternative to log4j
- Requests Library
- Collective example
- 无需显示屏的VNC Viewer远程连接树莓派
- MySQL semi sync replication
- Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it
- Power application of 5g DTU wireless communication module
猜你喜欢
What is the difference between one way and two way ANOVA analysis, and how to use SPSS or prism for statistical analysis
微搭低代码中实现增删改查
JMeter socket connection sends data
After 5 years of software testing in didi and ByteDance, it's too real
Usage of ViewModel and livedata in jetpack
Signal integrity (SI) power integrity (PI) learning notes (XXV) differential pair and differential impedance (V)
Decoupling pages and components using lifecycle
Design scheme of authority management of fusion model
WordPress add photo album function [advanced custom fields Pro custom fields plug-in series tutorial]
Modstart: embrace new technologies and take the lead in supporting laravel 9.0
随机推荐
Use of navigation and navigationui
Design and practice of vivo server monitoring architecture
Time unified system
Scrollview height cannot fill full screen
After 5 years of software testing in didi and ByteDance, it's too real
Common redis commands in Linux system
Analysis report on development trend and investment forecast of global and Chinese D-leucine industry from 2022 to 2028
The drawableleft of the custom textview in kotlin is displayed in the center together with the text
融合模型权限管理设计方案
部门新来的00后真是卷王,工作没两年,跳槽到我们公司起薪18K都快接近我了
Paint rounded rectangle
Registration method of native method in JNI
Working principle analysis of kubernetes architecture core components
Decoupling pages and components using lifecycle
JDBC - database connection
The new employee of the Department after 00 is really a champion. He has worked for less than two years. The starting salary of 18K is close to me when he changes to our company
Related operations of ansible and Playbook
How to quickly open traffic master for wechat applet
技术分享| WVP+ZLMediaKit实现摄像头GB28181推流播放
How to delete the entire row with duplicate items in a column of WPS table