1. How to use HttpClient
Public Staticstring loginbyclientget (string username,string password) {Try { //Open BrowserHttpClient client =Newdefaulthttpclient (); //enter address (URL)String url = "http://192.168.1.100:8088/Login.ashx?username=" +username+ "&password=" +password; HttpGet HttpGet=Newhttpget (URL); //Press ENTER (send request HTTP GET request)HttpResponse response =Client.execute (HttpGet); //get the corresponding code intCode =response.getstatusline (). Getstatuscode (); if(code==200) { //get the corresponding entityhttpentity entity =response.getentity (); //get the appropriate contentInputStream is =entity.getcontent (); returnStreamutil.readinputstream (IS); } Else { return NULL; } } Catch(Exception e) {e.printstacktrace (); return NULL; } } Public Staticstring loginbyclientpost (string username,string password) {Try { //Open BrowserHttpClient client =Newdefaulthttpclient (); //Enter address (enter URL)String url = "Http://192.168.1.100:8088/Login.ashx"; //using a POST requestHttpPost HttpPost =Newhttppost (URL); //Enter the data entity for the specified submissionlist<namevaluepair> params =NewArraylist<namevaluepair>(); Params.add (NewBasicnamevaluepair ("username", username)); Params.add (NewBasicnamevaluepair ("Password", password)); Httppost.setentity (Newurlencodedformentity (params)); //get the correspondingHttpResponse response =Client.execute (HttpPost); //Get the response code intCode =response.getstatusline (). Getstatuscode (); if(code==200) { //get the appropriate contentInputStream is =response.getentity (). getcontent (); returnStreamutil.readinputstream (IS); } Else { return NULL; } } Catch(Exception ex) {ex.printstacktrace (); return NULL; } }
2. InputStream to String method
Packagecom.example.getserverdata.utils;ImportJava.io.ByteArrayOutputStream;Importjava.io.IOException;ImportJava.io.InputStream; Public classStreamutil { Public StaticString Readinputstream (InputStream is) {Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); byte[] data =New byte[1024]; intLen = 0; Try { while(len = is.read (data))!=-1) baos.write (data,0, Len); Is.close (); Baos.close (); return NewString (Baos.tobytearray ()); } Catch(Exception e) {e.printstacktrace (); } return NULL; }}
Android HttpClient submit data to the server