HttpURLConnection Tool class for accessing the server using Get and post (i)

Source: Internet
Author: User

First we have an interface that returns a response Httpcallbacklistener

 Public  Interface   Httpcallbacklistener {    void  onfinish (String response);     void OnError (Exception e);}

And then the main body of the tool class.

ImportAndroid.util.Log;ImportOrg.json.JSONObject;ImportJava.io.BufferedReader;ImportJava.io.DataOutputStream;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;Importjava.net.HttpURLConnection;ImportJava.net.URL;ImportJava.net.URLEncoder;ImportJava.util.Map; Public classHttputil {//using the Get method, path stores a URL, and map stores a key-value pair     Public Static voidSendhttprequestforget (FinalString Path,Finalmap<string,string> params,FinalHttpcallbacklistener Listener) {        NewThread (NewRunnable () {@Override Public voidrun () {httpurlconnection connection=NULL; Try{StringBuilder StringBuilder=NewStringBuilder (); StringBuilder Response=NewStringBuilder (); Stringbuilder.append (Path). Append ("?"); if(params!=NULL&&params.size ()!=0){                         for(map.entry<string,string>Entry:params.entrySet ()) {                            //convert into UTF-8Stringbuilder.append (Entry.getkey ()). Append ("="). Append (Urlencoder.encode (Entry.getvalue (), "Utf-8")); Stringbuilder.append ("&"); }                        //Delete last character &Stringbuilder.deletecharat (Stringbuilder.length ()-1); }                    //The URL is longer, adding content from the mapURL url=NewURL (stringbuilder.tostring ()); //Print URLsLOG.E ("Httputil", stringbuilder.tostring ()); Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (100000); Connection.setreadtimeout (100000); Connection.setrequestproperty ("Content-type", "Application/json"); //200 indicates successful connection                    if(Connection.getresponsecode () ==200) {InputStream in=Connection.getinputstream (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (In, "Utf-8"));                        String Line;  while((Line=reader.readline ())! =NULL) {response.append (line); }                    }Else{System.out.println (Connection.getresponsecode ()); LOG.E ("Httputil", "fail"); }                    if(listener!=NULL) {LOG.E ("Httputil", response.tostring ()); //converts a response to a string type and then passes in as a parameter in order to invoke his class accessListener.onfinish (response.tostring ()); }                }Catch(Exception e) {if(listener!=NULL) {listener.onerror (e); }                }finally {                    if(connection!=NULL) {connection.disconnect ();    }}}). Start (); }     Public Static voidSendhttprequestforpost (FinalString Path,FinalMap<string,string> Paramsvalue,FinalHttpcallbacklistener Listener) {        NewThread (NewRunnable () {@Override Public voidrun () {httpurlconnection connection=NULL; Try{StringBuilder response=NewStringBuilder (); Jsonobject Jsonobject=NewJsonobject ();  for(map.entry<string,string>Entry:paramsValue.entrySet ())                    {Jsonobject.put (Entry.getkey (), Entry.getvalue ()); } URL URL=NewURL (path); Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("POST"); Connection.setconnecttimeout (100000); Connection.setreadtimeout (100000); Connection.setdooutput (true); Connection.setdoinput (true); //You must remember this setrequestproperty.Connection.setrequestproperty ("Content-type", "Application/json;charset=utf-8"); LOG.D ("Httputil", jsonobject.tostring ()); //write data to the serverDataOutputStream out=NewDataOutputStream (Connection.getoutputstream ());                    Out.writebytes (Jsonobject.tostring ()); LOG.D ("Httputil", jsonobject.tostring ()); //Success                    if(Connection.getresponsecode () ==200) {LOG.D ("Httputil", "Success"); InputStream in=Connection.getinputstream (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (In, "Utf-8"));                        String Line;  while((Line=reader.readline ())! =NULL) {response.append (line); }                    }Else{LOG.E ("Httputil", Integer.tostring (Connection.getresponsecode ())); LOG.E ("Httputil", "fail"); }                    if(listener!=NULL) {LOG.E ("Httputil", "registered successfully"); LOG.E ("Httputil", response.tostring ());                    Listener.onfinish (Response.tostring ()); }                }Catch(Exception e) {if(listener!=NULL) {LOG.D ("Httputil", E.getmessage ());                    Listener.onerror (e); }                }finally {                    if(connection!=NULL) {connection.disconnect ();    }}}). Start (); }}

Let's say we're going to visit in Mainactivity.

New Httpcallbacklistener () {                            @Override                            publicvoid  onfinish (String response) {                                 // It's a lot easier when you get response .                             }                            @Override                            publicvoid  onError (Exception e) {                            }                        } );

HttpURLConnection Tool class for accessing the server using Get and post (i)

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.