[Android] asynchronous HTTP framework and implementation principle

This paper introduces the development of asynchronous HTTP framework Android async http loopj on GitHub

Get the asynchttpclient object through new

Call the get (URL, responsehandler) method of the asynchttpclient object and send a get request. Parameters: URL is a path of string type, and responsehandler is an asynchttppresponsehandler object

To get the returned data, you need to re-use the onsuccess () method of asynchttppresponsehandler class and directly rewrite it in the form of anonymous internal class. The method is a callback function, and the parameter is the returned content string type

Override the onfailure () method and call it when the request fails.

Implement a simplified asynchronous HTTP framework

Our HTTP request goes through two stages:

1. Start the sub thread and execute an HTTP request in the sub thread

2. After the sub thread is executed, notify the UI to update the interface

Create a class called asynchttpclient and define a method called get (string path),

Start the sub thread in this method and directly rewrite the run method with new thread,

In the run method, get the httpclient object, get the httpget object, and call the execute () method of the httpclient object. At this time, you need to use the handler object to pass information to the main thread

Add a parameter myhandler object in the get () method, which inherits from the handler

Create a class called myhandler, inherit handler, and define two callback methods onsuccess and onfailure

Override the handlemessage () method, and judge the what attribute of the message object in this method. Call the onsuccess () method if successful and the onfailure () method if failed

When the sending is successful in the asynchttpclient class, call the SendMessage () method of the myhandler object. The parameter is the message object, and assign the what attribute and obj attribute of the message object

Then it is called in the main thread. The method used is the same as before. This is a design concept of the template method. One method is executed successfully and one method is executed failed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>