Today, I want to port an automatic sign-In applet using HttpClient to Android. Fortunately, the Android SDK comes with the HttpClient package. When reading the Android documentation, I found that the official website also provided an AndroidHttpClient that implemented the HttpClient interface. I searched the internet and found no articles about AndroidHttpClient. Of course, you can continue to use DefaultHttpClient, but Android httpclient customized for Android is naturally better.
Below are two HttpServlet tests:
Copy codeThe Code is as follows: public class LogIn extends HttpServlet {
/**
* Processes requests for both HTTP
* <Code> GET </code> and
* <Code> POST </code> methods.
*
* @ Param request servlet request
* @ Param response servlet response
* @ Throws ServletException if a servlet-specific error occurs
* @ Throws IOException if an I/O error occurs
*/
Protected void processRequest (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
Response. setContentType ("text/html; charset = UTF-8 ");
Request. setCharacterEncoding ("UTF-8 ");
PrintWriter out = response. getWriter ();
HttpSession session = request. getSession ();
String info = request. getParameter ("info ");
Session. setAttribute ("info", info );
Try {
/* TODO output your page here. You may use following sample code .*/
Out. println ("OK ");
} Finally {
Out. close ();
}
}
// <Editor-fold defaultstate = "collapsed" desc = "HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <Code> GET </code> method.
*
* @ Param request servlet request
* @ Param response servlet response
* @ Throws ServletException if a servlet-specific error occurs
* @ Throws IOException if an I/O error occurs
*/
@ Override
Protected void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
ProcessRequest (request, response );
}
/**
* Handles the HTTP
* <Code> POST </code> method.
*
* @ Param request servlet request
* @ Param response servlet response
* @ Throws ServletException if a servlet-specific error occurs
* @ Throws IOException if an I/O error occurs
*/
@ Override
Protected void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
ProcessRequest (request, response );
}
/**
* Returns a short description of the servlet.
*
* @ Return a String containing servlet description
*/
@ Override
Public String getServletInfo (){
Return "Short description ";
} // </Editor-fold>
}
Copy codeThe Code is as follows: public class Info extends HttpServlet {
/**
* Processes requests for both HTTP
* <Code> GET </code> and
* <Code> POST </code> methods.
*
* @ Param request servlet request
* @ Param response servlet response
* @ Throws ServletException if a servlet-specific error occurs
* @ Throws IOException if an I/O error occurs
*/
Protected void processRequest (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
Response. setContentType ("text/html; charset = UTF-8 ");
PrintWriter out = response. getWriter ();
HttpSession session = request. getSession ();
String info = (String) session. getAttribute ("info ");
Try {
/* TODO output your page here. You may use following sample code .*/
If (info = null)
Out. print ("null ");
Else
Out. print (info );
} Finally {
Out. close ();
}
}
// <Editor-fold defaultstate = "collapsed" desc = "HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <Code> GET </code> method.
*
* @ Param request servlet request
* @ Param response servlet response
* @ Throws ServletException if a servlet-specific error occurs
* @ Throws IOException if an I/O error occurs
*/
@ Override
Protected void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
ProcessRequest (request, response );
}
/**
* Handles the HTTP
* <Code> POST </code> method.
*
* @ Param request servlet request
* @ Param response servlet response
* @ Throws ServletException if a servlet-specific error occurs
* @ Throws IOException if an I/O error occurs
*/
@ Override
Protected void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
ProcessRequest (request, response );
}
/**
* Returns a short description of the servlet.
*
* @ Return a String containing servlet description
*/
@ Override
Public String getServletInfo (){
Return "Short description ";
} // </Editor-fold>
}
The main code is in processRequest. You do not need to check other codes.
When you access LogIn, a value with the name "info" is passed, and the browser will obtain a cookie used to locate the session on the server. Then access Info. If there is a cookie, the server can find the value you just passed and return it to you. If there is no cookie, it cannot be found.
Android code:Copy codeThe Code is as follows: public class MainActivity extends Activity {
Private AndroidHttpClient mHttpclient = AndroidHttpClient. newInstance ("");
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
FindViewById (R. id. button1). setOnClickListener (new OnClickListener (){
@ Override
Public void onClick (View v ){
// TODO Auto-generated method stub
New Thread (rTest). start ();
}
});
}
Private String toString (InputStream is) throws IOException {
String ret = "";
InputStreamReader isr = new InputStreamReader (is );
BufferedReader br = new BufferedReader (isr );
String tmp = br. readLine ();
While (tmp! = Null ){
Ret + = tmp;
Tmp = br. readLine ();
}
Br. close ();
Return ret;
}
Private Runnable rTest = new Runnable (){
@ Override
Public void run (){
// TODO Auto-generated method stub
Try {
BasicHttpContext context = new BasicHttpContext ();
Context. setAttribute (ClientContext. COOKIE_STORE, new BasicCookieStore ());
HttpPost httppost = new HttpPost ("http: // 10.226.233.48: 8080/WebApplication1/LogIn ");
List <NameValuePair> nvps = new ArrayList <NameValuePair> ();
Nvps. add (new BasicNameValuePair ("info", "Hello world !! "));
Httppost. setEntity (new UrlEncodedFormEntity (nvps, "UTF-8 "));
HttpResponse responsesponmhttpclient.exe cute (httppost, context );
HttpEntity entity = response. getEntity ();
Log. I ("kagami", MainActivity. this. toString (entity. getContent ()));
Entity. consumeContent ();
HttpGet httpget2 = new HttpGet ("http: // 10.226.233.48: 8080/WebApplication1/Info ");
HttpResponse response2%mhttpclient.exe cute (httpget2, context );
HttpEntity entity2 = response2.getEntity ();
Log. I ("kagami", MainActivity. this. toString (entity2.getContent ()));
Entity2.consumeContent ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
};
}
Differences between AndroidHttpClient and DefaultHttpClient:
AndroidHttpClient cannot execute in the main thread and will throw an exception. AndroidHttpClient obtains the instance through the static method newInstance. The parameter is a proxy. If no proxy is needed, enter "". By default, DefaultHttpClient enables cookies, while AndroidHttpClient does not enable cookies by default. To use DefaultHttpClient, you must add an HttpContext parameter each time you execute and add CookieStore. Do not forget to close after use. Otherwise, you cannot create a new instance.