Android http HttpURLConnection

Source: Internet
Author: User

 /**  * Http get  Request   *   *  @param  urlpath   *   *   */ private static string httpconnbyget ( Requesturl ru,params params) {   string token =  (String)   Params.getmap (). Get ("token")  ;  String et =  (String)  params.getmap (). Get (" ET ")  ;  params.getmap (). Remove (" et ");   if (token != null ) {    params.getmap (). Put ("token", Md5.md5 (Token + et + params.getmap (). Get ("UID")  +  ru.getkeywords ()));   }    string urlpath = ru.geturl ()  + HttpURLConstant.QMARK + HttpURLConstant.COMMON_PARAMS + et +  Params.tostring ()  ; //general parameter Settings   log.w ("Neturl", "Geturl:" +urlpath);   url url  = null;  httpurlconnection urlconnection = null;      try {    Bytearrayoutputstream outstream = new bytearrayoutputstream ();    byte[]  data = new byte[2048];    //should not be small!    int len = 0;   url = new url (UrlPath);       urlConnection =  (HttpURLConnection)  url.openconnection ();      //   class<?> clazz=url.openconnection (). GetClass ();   //Look back what kind of ghost type//   class<?> clazzsuper=clazz.getsuperclass ();    What the hell is the     //father class?          //getinputstream secretly performed the connection, do not need urlconnection.connect ();    urlconnection.setreadtimeout (readtimeout);                                                     //  set the Request Timeout time    urlconnection.setconnecttimeout (connecttimeout);    if   (Urlconnection.getresponsecode () &NBSP;==&NBSP;HTTPURLCONNECTION.HTTP_OK)  {          inputstream instream = urlconnection.getinputstream ();    //gets the input stream, at which point it really builds the link     while  (len = instream.read (data))  !=  -1)  {     outstream.write (Data, 0, len);     }        instream.close ();        if (Isdebug) {LOG.E (TAG, "get  return Data" +new string (Outstream.tobytearray ()));}     return new string (Outstream.tobytearray ());    }else{ //returns the HTTP error code, not our own definition of the error code!         //Handle HTTP Error return code         &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.E (TAG, "get  network Connection Failed" +urlconnection.getresponsecode ());     return  "http_error-" +urlconnection.getresponsecode ();    }  } catch   (malformedurlexception e)  {   e.printstacktrace (); &NBSP;&NBSP;&NBSP;LOG.E (TAG, " Malformedurlexception e ");  } catch  (ioexception e)  {    E.printstacktrace (); &NBSP;&NBSP;&NBSP;LOG.E (TAG, "ioexception e");  } finally{           if (urlconnection!=null) {     Urlconnection.disconnect ();   //always need to be closed!    }     }  return null;   }               /**  * http post  Request    *  *  @param  urlpath  *  @param  paramsDatas  */  Private static string httpconnbypost (Requesturl ru,params params)  {   string token =  (String)  params.getmap (). Get ("token")  ;  string et  =  (String)  params.getmap (). Get ("et")  ;  params.getmap (). Remove ("et");   if (token != null ) {   params.getmap (). Put ("token", &NBSP;MD5.MD5 (token  + et + params.getmap (). Get ("UID")  + ru.getkeywords ()));  }     URL url = null;                                                          //  Create a URL object based on an address   HttpURLConnection urlConnection = null;                                 //  open a link based on a URL object   try  {   url = new url (Ru.geturl ());                                                             //  Create URL objects based on address    urlConnection =  (HttpURLConnection)  url.openconnection ();                              //  Open link       urlconnection.setrequestmethod ("POST") based on URL object;                                                  //  How to set the request     Urlconnection.setreadtimeout (readtimeout);                                              //  set the time-out for the request    urlconnection.setconnecttimeout (connecttimeout);          String paramsData = httpurlconstant.common_params + et + params.tostring ();            //the use of general parameters to pay attention to &NBSP;&NBSP;&NBSP;LOG.W ("Neturl", url+ "?" +paramsdata);       urlconnection.setrequestproperty ("Connection",  " Keep-alive ");                          //  Setup to maintain long connections       Urlconnection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); //  settings file type    urlconnection.setrequestproperty ("Content-length", String.valueof (ParamsData.getBytes (). Length); //  Set the data    urlconnection.setrequestproperty ("User-agent", "Devond_Watch, Android-device. ");   // ???    urlconnection.setdooutput (TRUE);   //  send POST request must set allow output     Urlconnection.setdoiNput (True);    //  send a POST request must be set to allow input, setdoinput default value is true    Urlconnection.setusecaches (False); //  is safe and does not allow caching           urlconnection.connect ();            // Urlconnection.getinputstream () will automatically open the connected    OutputStream os =  Urlconnection.getoutputstream ();     //gets the output stream Developer   os.write ( Paramsdata.getbytes ());    os.flush ();      if  ( Urlconnection.getresponsecode () &NBSP;==&NBSP;HTTPURLCONNECTION.HTTP_OK)  {                      inputstream  is = urlconnection.getinputstream ();           //  gets the input stream object of the response     bytearrayoutputstream baos =&Nbsp;new bytearrayoutputstream (); //  create byte output stream object     int len =  0;                                                //  define the length of the read     byte  buffer[] = new byte[2048];                            //  Defining buffers     while  ((len = is.read (buffer))  != -1)  {                    //  Loop through      baos.write (Buffer, 0, len) According to the size of the buffer;                               writes to the OS object based on the length of the Read     }    is.close ();//  frees the resources         baos.close ();       final string result  = new string (Baos.tobytearray ());         if (IsDebug) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.E (TAG, "Post returned data:" +result);    }      return new string (Baos.tobytearray ());        }else{ // The error code returned is HTTP, not our own definition of the error code!     //Handle HTTP Error return code &NBSP;&NBSP;&NBSP;&NBSP;LOG.E (Tag,urlconnection.getresponsecode () + "# post  Network Connection Failed # "+urlconnection.geterrorstream ());    return " HTTP_ERROR-"+ Urlconnection.getresponsecode ();   }  } catch  (MalformedURLException e ) {   e.printstacktrace (); &NBSP;&NBSP;&NBSP;LOG.E (TAG, "malformedurlexception e");   }catch  (exception e)  {   e.printstacktrace ();   }finally{       if (urlconnection!=null) {    urlconnection.disconnect () ; &NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;LOG.E (TAG, "post  request returned to null");   return null; }

Android http HttpURLConnection

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.