Android HTTP Tool Encapsulation class

Source: Internet
Author: User

* HTTP Tool class (with Java fallback mechanism) [Note: UI update is still not possible, still in the sub-thread operation]
* When using HTTP for network interaction multiple times, it can be encapsulated in a class
* How to use:
* First to build an interface class: The following:
* Public Interface httpcallbacklistener{
* void OnFinish (String response)
* void OnError (Exception e)
* }
* Finally in the call class using
* Httputil.sendhttpresquest (address,new Httpcallbacklistener () {
* @Override
* public void OnFinish (String response) {
*//here to handle return data operation logic
* }
* @Override
* Pubic void OnError (Exception e) {
*//here to deal with the abnormal situation
* })
* (Java's callback mechanism is used to solve the problem when the server has not yet responded with the end of the execution ....) That is, the time problem, with a callback does not end the method)

Public class httputil{
public static void Sendhttprequest (final String address,final Httpcallbacklistener Listener) {
New Thread (new Runnable () {
public void Run () {
HttpURLConnection connection = null; try{
URL url = new URL (address);
Connection = (httpurlconnection) url.openconnection ();
Connection.setrequestmethod ("GET");
Connection.setconnecttimeout (800);
Connection.setreadtimeout (8000);
Connection.setdoinput (TRUE);
Connection.setdoouput (TRUE);
InputStream in = Connection.getinputstream ();
BufferedReader reader = new BufferedReader (new InputStreamReader (in));
StringBuilder response = new StringBuilder ();
String Line;
while (line = Reader.readline ())! = null) {
Response.append (line);
if (listener! = null) {
Listener.onfinish (response.tostring ());

}catch (Exception e) {
Listener.onerror (e);
if (connection! = null) {
Connection.disconnect ();

}). Start ();

Android HTTP Tool Encapsulation class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.