AndroidHttpClient使用Cookie应用分析
2023-06-13 09:14:41 时间
今天想把一个用使用了HttpClient的自动签到小程序移植到Android上,还好Android的SDK自带了HttpClient的包。翻Android的文档时发现官方还提供了一个实现了HttpClient接口的AndroidHttpClient,上网搜了下没发现关于AndroidHttpClient的文章。当然也可以继续使用DefaultHttpClient,但用为Android定制的AndroidHttpClient自然更好。
下面是2个测试用的HttpServlet:
复制代码代码如下:
下面是2个测试用的HttpServlet:
publicclassLogInextendsHttpServlet{
/**
*ProcessesrequestsforbothHTTP
*<code>GET</code>and
*<code>POST</code>methods.
*
*@paramrequestservletrequest
*@paramresponseservletresponse
*@throwsServletExceptionifaservlet-specificerroroccurs
*@throwsIOExceptionifanI/Oerroroccurs
*/
protectedvoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("utf-8");
PrintWriterout=response.getWriter();
HttpSessionsession=request.getSession();
Stringinfo=request.getParameter("info");
session.setAttribute("info",info);
try{
/*TODOoutputyourpagehere.Youmayusefollowingsamplecode.*/
out.println("OK");
}finally{
out.close();
}
}
//<editor-folddefaultstate="collapsed"desc="HttpServletmethods.Clickonthe+signonthelefttoeditthecode.">
/**
*HandlestheHTTP
*<code>GET</code>method.
*
*@paramrequestservletrequest
*@paramresponseservletresponse
*@throwsServletExceptionifaservlet-specificerroroccurs
*@throwsIOExceptionifanI/Oerroroccurs
*/
@Override
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
processRequest(request,response);
}
/**
*HandlestheHTTP
*<code>POST</code>method.
*
*@paramrequestservletrequest
*@paramresponseservletresponse
*@throwsServletExceptionifaservlet-specificerroroccurs
*@throwsIOExceptionifanI/Oerroroccurs
*/
@Override
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
processRequest(request,response);
}
/**
*Returnsashortdescriptionoftheservlet.
*
*@returnaStringcontainingservletdescription
*/
@Override
publicStringgetServletInfo(){
return"Shortdescription";
}//</editor-fold>
}
publicclassInfoextendsHttpServlet{
/**
*ProcessesrequestsforbothHTTP
*<code>GET</code>and
*<code>POST</code>methods.
*
*@paramrequestservletrequest
*@paramresponseservletresponse
*@throwsServletExceptionifaservlet-specificerroroccurs
*@throwsIOExceptionifanI/Oerroroccurs
*/
protectedvoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.setContentType("text/html;charset=UTF-8");
PrintWriterout=response.getWriter();
HttpSessionsession=request.getSession();
Stringinfo=(String)session.getAttribute("info");
try{
/*TODOoutputyourpagehere.Youmayusefollowingsamplecode.*/
if(info==null)
out.print("null");
else
out.print(info);
}finally{
out.close();
}
}
//<editor-folddefaultstate="collapsed"desc="HttpServletmethods.Clickonthe+signonthelefttoeditthecode.">
/**
*HandlestheHTTP
*<code>GET</code>method.
*
*@paramrequestservletrequest
*@paramresponseservletresponse
*@throwsServletExceptionifaservlet-specificerroroccurs
*@throwsIOExceptionifanI/Oerroroccurs
*/
@Override
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
processRequest(request,response);
}
/**
*HandlestheHTTP
*<code>POST</code>method.
*
*@paramrequestservletrequest
*@paramresponseservletresponse
*@throwsServletExceptionifaservlet-specificerroroccurs
*@throwsIOExceptionifanI/Oerroroccurs
*/
@Override
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
processRequest(request,response);
}
/**
*Returnsashortdescriptionoftheservlet.
*
*@returnaStringcontainingservletdescription
*/
@Override
publicStringgetServletInfo(){
return"Shortdescription";
}//</editor-fold>
}
主要代码在processRequest里,其他可以不用看。
访问LogIn时传一个name为info的值,这时浏览器会得到一个用于定位服务端session的cookie。然后访问Info,如果有cookie的话服务端能找到刚才你传的值并返回给你,没带cookie的话就不能找到。
Android端代码:
publicclassMainActivityextendsActivity{
privateAndroidHttpClientmHttpclient=AndroidHttpClient.newInstance("");
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
//TODOAuto-generatedmethodstub
newThread(rTest).start();
}
});
}
privateStringtoString(InputStreamis)throwsIOException{
Stringret="";
InputStreamReaderisr=newInputStreamReader(is);
BufferedReaderbr=newBufferedReader(isr);
Stringtmp=br.readLine();
while(tmp!=null){
ret+=tmp;
tmp=br.readLine();
}
br.close();
returnret;
}
privateRunnablerTest=newRunnable(){
@Override
publicvoidrun(){
//TODOAuto-generatedmethodstub
try{
BasicHttpContextcontext=newBasicHttpContext();
context.setAttribute(ClientContext.COOKIE_STORE,newBasicCookieStore());
HttpPosthttppost=newHttpPost("http://10.226.233.48:8080/WebApplication1/LogIn");
List<NameValuePair>nvps=newArrayList<NameValuePair>();
nvps.add(newBasicNameValuePair("info","你好世界!!"));
httppost.setEntity(newUrlEncodedFormEntity(nvps,"utf-8"));
HttpResponseresponse=mHttpclient.execute(httppost,context);
HttpEntityentity=response.getEntity();
Log.i("kagami",MainActivity.this.toString(entity.getContent()));
entity.consumeContent();
HttpGethttpget2=newHttpGet("http://10.226.233.48:8080/WebApplication1/Info");
HttpResponseresponse2=mHttpclient.execute(httpget2,context);
HttpEntityentity2=response2.getEntity();
Log.i("kagami",MainActivity.this.toString(entity2.getContent()));
entity2.consumeContent();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
};
}
AndroidHttpClient和DefaultHttpClient的区别:
AndroidHttpClient不能在主线程中execute,会抛出异常。AndroidHttpClient通过静态方法newInstance获得实例,参数是代理,不用代理的话填“”。DefaultHttpClient默认是启用Cookie的,AndroidHttpClient默认不启用Cookie,要使用的话每次execute时要加一个HttpContext参数,并且添加CookieStore。用完后别忘了close不然不能创建新实例。
相关文章
- 来!新闻流与股价跳跃、图数据应用综述、机器学习与有效前沿
- 单细胞测序在卵巢癌中的研究应用
- 通过 KoP 将 Kafka 应用迁移到 Pulsar
- 【Android 插件化】VirtualApp 源码分析 ( 目前的 API 现状 | 安装应用源码分析 | 安装按钮执行的操作 | 返回到 HomeActivity 执行的操作 )
- MySQL中时间戳函数的实践应用(mysql时间戳函数)
- 缓存实现面向Java应用的Redis过期缓存技术(redisjava过期)
- Oracle内存透明大页技术革命性应用(oracle内存透明大页)
- MySQL语句在C语言中的应用(C 中的mysql语句)
- Oracle全文函数介绍及应用技巧(oracle 全文函数)
- 使用Redis连接提升安全全局锁的应用(redis连接加了全局锁)
- php学习笔记php中面向对象三大特性之一[封装性]的应用