AndroidHttpClient使用Cookie应用分析

2016-02-19 11:34 10 1 收藏

最近很多朋友喜欢上设计,但是大家却不知道如何去做,别担心有图老师给你解答,史上最全最棒的详细解说让你一看就懂。

【 tulaoshi.com - 编程语言 】

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

public class LogIn extends HttpServlet {
/**
* Processes requests for both HTTP
* codeGET/code and
* codePOST/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
* codeGET/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
* codePOST/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
}

代码如下:

public class Info extends HttpServlet {
/**
* Processes requests for both HTTP
* codeGET/code and
* codePOST/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
* codeGET/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
* codePOST/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
}

主要代码在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 NameValuePair nvps = new ArrayList NameValuePair();
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不然不能创建新实例。

来源:http://www.tulaoshi.com/n/20160219/1597892.html

延伸阅读
标签: Web开发
//写cookie操作 Cookie cooki; cooki=new Cookie("bbs_0001",String.valueOf(num));//用户ID cooki.setMaxAge(60*60*24*365);//cookie时间 cooki.setPath("/"); //根据个人的不用,在不同功能的路径下创建 response.addCookie(cooki); //清空Cookie操作 Cookie[] cookies=request.getCookies(); try { for(int i=0;icookies.length;i+...
以下内容来自MSDN 数组是具有相同数据类型的项的有序集合。要访问数组中的某个项,需要同时使用数组名称及该项与数组起点之间的偏移量。在 C# 中,声明和使用数组的方法与 Java 有一些重要区别。  一维数组  一维数组以线性方式存储固定数目的项,只需一个索引值即可标识任意一个项。在 C# 中,数...
标签: Web开发
困扰我N天的问题终于解决了,当我用.NET写采集器的时候,遇到需要登陆的问题,这时就要设置COOKIE 可是我怎么设置它都不行,后来通过嗅探嗅探数据发现,原来我设置的COOKIE只设置了一半,container.SetCookies(uri,cookie)方法只设置分号前的部分,当我把COOKIE分离后一个一个添加时发现,一切都解决了。    1 pri...
一、在活动的应答项中设置cookie,以及在请求中读同样的cookie. 把Cookies 设置为应答的一部分,使用SetCookieField方法: TStringList* Cookies = new TStringList(); Cookies-Add("Answer=42"); // whatever... Response-SetCookieField(Cookies,NULL,NULL,Now()+1,false); Cookies-Free(); ...
标签: PHP
最近发现写博客也是提高 javascript :;" onClick="javascript:tagshow(event, '%D1%A7%CF%B0');" target="_self"> 学习 效率的有效途径之一。好记性不如烂笔头,归纳总结时,你会发现总有一些东西你认为很熟了,它却在细微处讽刺你的错误。我学习COOKIE与SESSION时,几乎把社区所有相关的帖子都下载了,研究过后,总结了这么点东...

经验教程

73

收藏

64
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部