Androidhttpclient Use cookie Application analysis _java

Source: Internet
Author: User
Today I want to transplant an automatic check-in applet with a httpclient to Android, but the Android SDK is packed with httpclient. Turning to the Android document found that the official also provided a httpclient interface to achieve the androidhttpclient, the Internet search did not find the article about androidhttpclient. Of course, you can continue to use defaulthttpclient, but the androidhttpclient for Android is naturally better.
here are 2 test HttpServlet.
Copy Code code as follows:

public class LogIn extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code>
* <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. 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 Code code as follows:

public class Info extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code>
* <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. 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 in the ProcessRequest, others can not see.
When you visit login, you pass a value of name info, and the browser gets a cookie to locate the server session. Then visit info, and if there is a cookie, the server can find the value you just sent and return it to you without a cookie.
Android Side code:
Copy Code code 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 Response=mhttpclient.execute (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.execute (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 ();
}
}
};



the difference between androidhttpclient and defaulthttpclient
Androidhttpclient cannot execute in the main thread and throws an exception. Androidhttpclient through static method Newinstance Obtain the instance, the parameter is the proxy, does not need the agent to fill in "". Defaulthttpclient is enabled by default, Androidhttpclient does not enable cookies by default, and a HttpContext parameter is added to each execute when you use it, and you add Cookiestore. Don't forget close when you are done. You cannot create a new instance.

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.