当前位置:  编程技术>java/j2ee

AndroidHttpClient使用Cookie应用分析

    来源: 互联网  发布时间:2014-10-22

    本文导语:  今天想把一个用使用了HttpClient的自动签到小程序移植到Android上,还好Android的SDK自带了HttpClient的包。翻Android的文档时发现官方还提供了一个实现了HttpClient接口的AndroidHttpClient,上网搜了下没发现关于AndroidHttpClient的文章。当...

今天想把一个用使用了HttpClient的自动签到小程序移植到Android上,还好Android的SDK自带了HttpClient的包。翻Android的文档时发现官方还提供了一个实现了HttpClient接口的AndroidHttpClient,上网搜了下没发现关于AndroidHttpClient的文章。当然也可以继续使用DefaultHttpClient,但用为Android定制的AndroidHttpClient自然更好。
下面是2个测试用的HttpServlet:
代码如下:

public class LogIn extends HttpServlet {
/**
* Processes requests for both HTTP
* GET and
* POST 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();
}
}
//
/**
* Handles the HTTP
* GET 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
* POST 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";
}//
}

代码如下:

public class Info extends HttpServlet {
/**
* Processes requests for both HTTP
* GET and
* POST 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();
}
}
//
/**
* Handles the HTTP
* GET 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
* POST 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";
}//
}

主要代码在processRequest里,其他可以不用看。
访问LogIn时传一个name为info的值,这时浏览器会得到一个用于定位服务端session的cookie。然后访问Info,如果有cookie的话服务端能找到刚才你传的值并返回给你,没带cookie的话就不能找到。
Android端代码:
代码如下:

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 nvps = new ArrayList ();
nvps.add(new BasicNameValuePair("info", "你好 世界!!"));
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();
}
}
};


 
AndroidHttpClient和DefaultHttpClient的区别:
AndroidHttpClient不能在主线程中execute,会抛出异常。AndroidHttpClient通过静态方法newInstance获得实例,参数是代理,不用代理的话填“”。DefaultHttpClient默认是启用Cookie的,AndroidHttpClient默认不启用Cookie,要使用的话每次execute时要加一个HttpContext参数,并且添加CookieStore。用完后别忘了close不然不能创建新实例。

    
 
 

您可能感兴趣的文章:

 
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3