Dhroid-dhnet Network HTTP Tools

Source: Internet
Author: User

extends:http://www.eoeandroid.com/thread-327440-1-1.html 
        Dhnet net=New dhnet ("Lu Jin");        Net.addparam ("key", "parameter")           . AddParam ("Key2", "Parameter 2");           . Doget (new nettask (this) {             @Override              publicvoid Doinui (Response Response, Integer transfer) {                                // process return result               }        

The above is the most commonly used methodcreating a Dhnet Object Dhnet object Most methods are to support chained operations;

the value of the Add parameter AddParam can be any object, and if not NULL, the ToString method is called,
If the argument is TextView or its subclass or call Method GetText (). toString ();

Get or Post methodcan call
Net.setmethod ("Get or post") or Net.doget (new nettask (this) {xxx}); Net.dopost ( New Nettask (this) {XXX})


About dialog Boxes
Net.dogetindialog (new nettask (this) {xxx}); // get opens a dialog box net.dopostindialog (new nettask (this) {xxx}); // Post also opens a dialog box net.doget (truenew nettask (this) {xxx}); // whether the first parameter displays a dialog box

the text in the dialog box is default get when loaded ..., post is for submission ...if you want to rewrite
Net.setdialogermsg ("dialog box Information");



See Nettask Callback class belowa few main methods
// When an error occurs, the callback is in the UI thread  Public void Onerray (Response Response) // returning data will now be processed in the background  Public void Doinbackground (Response response1) // Finally, the UI thread will process  Public void

something needs to be handled during doinbackground processing the UI can then be
//Add code in Doinbackground         Public voidDoinbackground (Response Response) {Super. Doinbackground (response); //to add a passed object in the responseResponse.addbundle ("Key", "Object Pass"); //passed to UI, the second parameter is custom encodedTransfer (response, 100); }//in the Doinui         Public voidDoinui (Response Response, Integer transfer) {if(transfer==100){         //gets the passed objectObject obj=response.getbundle ("Key")     }     }

Here's a look at the response objectResponse object refers to the returned dataThere are many ways to response
String Res=response.plain ()// can get network access to plain text

of course, our basic network access is JSON .

jsonobject Jo=response.json ()//JSON object that can return network access


Network default best return format, of course not required

{     success:true,     msg:' message content ',     code:' ERROR '     data:{}}

the corresponding configurationhere is the configuration in the const you can overwrite
{     success:true,     msg:' message content ',     code:' ERROR '      data:{}}


with these,
//assume that the returned result{success:true, data:{user:{ID:1212, Name:' Tengzhinei '}}, articles:[{ID:1}, {ID:2}    ]   }        //JSON processingBooleanSuccess=response.issuccess ();//is successful,Jsonobject Jo = Response.jsonfromdata ();//gets the object under the data nodeJsonobject data = Response.jsonfrom ("data");;//gets the object under the data nodeJsonobject user = Response.jsonfrom ("Data.user");//gets the object under the Data.user nodeJsonarray array = response.jsonarrayfrom ("Data.articles");//gets the array under the Data.articles node//You can also convert the JSON directly to a beanUser user = Response.modelfrom ("Data.user", user.class);//you can get to the user object directly (generics are used here)List<article> articles = Response.listfrom (User.class, "Data.articles")//get an array of objects

response is very powerful.




here, by the way, Viewutil and Jsonutil.Here are the data binding methods I like to use
         "Time"), "Time"); // The first parameter view can be a textview or its subclasses, ImageView // If it is ImageView  if the second argument is a string will automatically download the picture if it is drawable,bitmap,int or get directly bound picture // second Number data // Third Number data decoration   // The data is decorated as a time type, and the specific cosmetic problem is adapter to talk about it later.

go on, say that Dhnet has a powerful network cache, let's say how to use it.
Dhnet net=Newdhnet (); Net.seturl ("Http://youxianpei.c.myduohuo.com/mobile_index_adbjsonview?id=63&temp=cache_net_error");//look here, using a cache policyNet.usecache (Cachepolicy.policy_on_net_error); Net.doget (NewNettask (getactivity ()) {@Override Public voidDoinui (Response Response, Integer transfer) {//response have a way of judging whether the result is a cache        if(!Response.iscache ()) {Dialoger.showtoastshort (Getactivity (),"This visit is not a cache to use, try to disconnect the network"); }Else{Dialoger.showtoastshort (getactivity (),"Network access failed, this time using cache"); }   }});

Net.usecache (CACHEPOLICY.XXX);//You can add a cache policynow there are caching policies//do not use cachePolicy_nocache; //Use only cachepolicy_cache_only; //the cache is used first, and then the obtained data is only cached.Policy_cache_andrefresh; //caching is only used when the network is badPolicy_on_net_error; //use the cache first, then get it, and then use it when you get it.policy_before_and_after_net;  These caching strategies are well understood, and the only thing that needs to be said is that the Doinbackground and Doinui of other policy_before_and_after_net policies will only be recalled once but policy_before_and_after_net Doinbackground and Doinui may be called back two times, once the last cache (if not the last cache, of course not callback), a real network of data acquired//network caching is simple.

in telling everybody a cheats
Const.net_error_try=True

If this value is set to true, errors that occur in Doinbackground and Doinui will be try-catch after the main project is on-line,

the project is still false during the development process.

upload the following file
Dhnet net=NewDhnet ("Path"); Net.addparam ("Key1", "Parameter 1"). AddParam ("Key2", "Parameter 2"). Upload ("File parameter name", files,NewNettask ( This) {@Override Public voidDoinui (Response Response, Integer transfer) {if(Response.issuccess ()) {Boolean uploading= Response.getbundle ("Uploading"); if(!uploading) {                                         //Upload Complete}Else{                                      //uploaded size                                     LongLength= response.getbundle ("Length"); //Total File Size                                   LongTotal= response.getbundle ("Total"); }                  }       }                });



//The above code is a file upload, mainly using the Upload method

Doinui will be called multiple times to process progress, response uploading,length,total three parameters to determine the progress



final File Download
// file download needs to be injected @InjectDownLoadManager Downloader; // Start Download downloader.download ("Task Code", "Road Strength", params, "Local save Path"); // third parameter additional parameters // Register to download the monitor downloader.regeistercallback ("Task Code", Downloadcallback); // Cancel the download of monitoring downloader.unregeistercallback ("Task Code");



you can listen to the activity's onresume, onstop, especially those that need to display the download progress in the ListView.



about synchronizing network access, these don't say
      Netutil.sync (URL, method, params);       Netutil.syncstream (URL, method, params);

back Ground
     Httpmanager.execute (HttpGet);

dhnet Network on these things, basically involved in all aspects of the network

Dhroid-dhnet Network HTTP Tools

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: info-contact@alibabacloud.com 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.