Send get and POST requests in the main thread update UI in Android thread

Source: Internet
Author: User

 Public classGetpostutil {/** * a request to send a GET method to a specified URL * * @param URL * Send the requested URL * @param params *      Request parameters, request parameters should be in the form of name1=value1&name2=value2. * @return The response of the remote resource represented by the URL*/       Public StaticString sendget (string URL, stringparams) {String result=""; BufferedReaderinch=NULL; Try{String urlname= URL +"?"+params; URL Realurl=NewURL (urlname); //opening and linking between URLsURLConnection conn =realurl.openconnection (); //to set common request propertiesConn.setrequestproperty ("Accept","*/*"); Conn.setrequestproperty ("Connection","keep-alive"); Conn.setrequestproperty ("user-agent",                  "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); //establish an actual connectionConn.connect (); //Get all response header fieldsmap<string, list<string>> map =Conn.getheaderfields (); //iterate through all the response header fields             for(String key:map.keySet ()) {System. out. println (Key +"--->"+ map.Get(key)); }              //defines the response of the BufferedReader input stream to read the URL            inch=NewBufferedReader (NewInputStreamReader (Conn.getinputstream ()));              String Line;  while(line =inch. ReadLine ())! =NULL) {result+="\ n"+Line ; }          }          Catch(Exception e) {System. out. println ("send GET request exception! "+e);          E.printstacktrace (); }          //Use the finally block to close the input stream        finally          {              Try              {                  if(inch!=NULL)                  {                      inch. Close (); }              }              Catch(IOException ex) {ex.printstacktrace (); }          }          returnresult; }        /** * a request to send a POST method to a specified URL * * @param URL * Send the requested URL * @param params *       Request parameters, request parameters should be in the form of name1=value1&name2=value2. * @return The response of the remote resource represented by the URL*/       Public StaticString sendpost (string URL, stringparams) {PrintWriter out=NULL; BufferedReaderinch=NULL; String result=""; Try{URL Realurl=Newurl (URL); //opening and linking between URLsURLConnection conn =realurl.openconnection (); //to set common request propertiesConn.setrequestproperty ("Accept","*/*"); Conn.setrequestproperty ("Connection","keep-alive"); Conn.setrequestproperty ("user-agent",                  "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); //to send a POST request, you must set the following two linesConn.setdooutput (true); Conn.setdoinput (true); //gets the output stream corresponding to the URLConnection object             out=NewPrintWriter (Conn.getoutputstream ()); //Send Request Parameters             out. Print (params); //buffer for flush output stream             out. Flush (); //defines the response of the BufferedReader input stream to read the URL            inch=NewBufferedReader (NewInputStreamReader (Conn.getinputstream ()));              String Line;  while(line =inch. ReadLine ())! =NULL) {result+="\ n"+Line ; }          }          Catch(Exception e) {System. out. println ("An exception occurred while sending the POST request! "+e);          E.printstacktrace (); }          //Use the finally block to close the output stream, input stream        finally          {              Try              {                  if( out!=NULL)                  {                       out. Close (); }                  if(inch!=NULL)                  {                      inch. Close (); }              }              Catch(IOException ex) {ex.printstacktrace (); }          }          returnresult; }  }  

Activity

 Public classGetpostmain extends Activity {ButtonGet, Post;      EditText Show; @Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);          Setcontentview (R.layout.main); Get= (Button) Findviewbyid (r.id.Get); Post=(Button) Findviewbyid (r.id.post); Show=(EditText) Findviewbyid (r.id.show); //updating the UI with handlerFinal Handler h =NewHandler () {@Override Public voidhandlemessage (Message msg) {if(msg.what==0x123) {Show.settext (msg.obj.toString ());                    }              }          }; Get. Setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {NewThread (NewAccessnetwork ("GET","http://192.168.1.88:8080/abc/a.jsp",NULL, h)).              Start ();          }                     }); Post.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {NewThread (NewAccessnetwork ("POST","http://192.168.1.88:8080/abc/login.jsp","Name=crazyit.org&pass=leegang", h)).              Start ();       }                     }); }  }  classAccessnetwork implements runnable{PrivateString op; PrivateString URL; PrivateStringparams; PrivateHandler H;  PublicAccessnetwork (string op, String URL, stringparams, Handler h)          {super ();  This. Op =op;  This. url =URL;  This.params=params;  This. H =h; } @Override Public voidrun () {Message m=NewMessage (); M.what=0x123; if(Op.equals ("GET") {log.i ("IIIIIII","send a GET request"); M.obj= Getpostutil.sendget (URL,params); LOG.I ("IIIIIII",">>>>>>>>>>>>"+m.obj); }          if(Op.equals ("POST") {log.i ("IIIIIII","send a POST request"); M.obj= Getpostutil.sendpost (URL,params); LOG.I ("GGGGGGGG",">>>>>>>>>>>>"+m.obj);      } h.sendmessage (M); }  }  

Send get and POST requests in the main thread update UI in Android thread

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.