今天想把一個用使用了HttpClient的自動簽到小程式移植到Android上,還好Android的SDK自備了HttpClient的套件。翻Android的文件時發現官方也提供了一個實作了HttpClient介面的AndroidHttpClient,上網搜了下沒發現關於AndroidHttpClient的文章。當然也可以繼續使用DefaultHttpClient,但用為Android客製化的AndroidHttpClient自然更好。
下面是2個測試用的HttpServlet :
複製代碼代碼如下:
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>
}
複製代碼代碼如下:
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>
}
主要程式碼在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不然不能建立新實例。