Android HttpServlet Json 資料互動

來源:互聯網
上載者:User

標籤:des   android   style   blog   http   io   ar   color   os   

Android 對其訪問進行封裝

Callable是類似於Runnable的介面,實現Callable介面的類和實現Runnable的類都是可被其它線程執行的任務。
Callable和Runnable有幾點不同:
 (1)Callable規定的方法是call(),而Runnable規定的方法是run().
 (2)Callable的任務執行後可傳回值,而Runnable的任務是不能傳回值的。
 (3)call()方法可拋出異常,而run()方法是不能拋出異常的。
 (4)運行Callable任務可拿到一個Future對象,
Future 表示非同步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,並檢索計算的結果。
通過Future對象可瞭解任務執行情況,可取消任務的執行,還可擷取任務執行的結果。

 

用戶端通過Json擷取服務端資料

/** * */package org.crazyit.auction.client.util;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.concurrent.Callable;import java.util.concurrent.FutureTask;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;/** * Description: * <br/>網站: <a href="http://www.crazyit.org">瘋狂ava聯盟</a> * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author  Yeeku.H.Lee [email protected] * @version  1.0 */public class HttpUtil{    // 建立HttpClient對象    public static HttpClient httpClient = new DefaultHttpClient();    public static final String BASE_URL =        "http://10.10.9.51:8080/auction/android/";    /**     *     * @param url 發送請求的URL     * @return 伺服器響應字串     * @throws Exception     */    public static String getRequest(final String url)        throws Exception    {        FutureTask<String> task = new FutureTask<String>(        new Callable<String>()        {            @Override            public String call() throws Exception            {                // 建立HttpGet對象。                HttpGet get = new HttpGet(url);                // 發送GET請求                HttpResponse httpResponse = httpClient.execute(get);                // 如果伺服器成功地返迴響應                if (httpResponse.getStatusLine()                    .getStatusCode() == 200)                {                    // 擷取伺服器響應字串                    String result = EntityUtils                        .toString(httpResponse.getEntity());                    return result;                }                return null;            }        });        new Thread(task).start();        return task.get();    }    /**     * @param url 發送請求的URL     * @param params 請求參數     * @return 伺服器響應字串     * @throws Exception     */    public static String postRequest(final String url        , final Map<String ,String> rawParams)throws Exception    {        FutureTask<String> task = new FutureTask<String>(        new Callable<String>()        {            @Override            public String call() throws Exception            {                // 建立HttpPost對象。                HttpPost post = new HttpPost(url);                // 如果傳遞參數個數比較多的話可以對傳遞的參數進行封裝                List<NameValuePair> params =                     new ArrayList<NameValuePair>();                for(String key : rawParams.keySet())                {                    //封裝請求參數                    params.add(new BasicNameValuePair(key                         , rawParams.get(key)));                }                // 佈建要求參數                post.setEntity(new UrlEncodedFormEntity(                    params, "gbk"));                // 發送POST請求                HttpResponse httpResponse = httpClient.execute(post);                // 如果伺服器成功地返迴響應                if (httpResponse.getStatusLine()                    .getStatusCode() == 200)                {                    // 擷取伺服器響應字串                    String result = EntityUtils                        .toString(httpResponse.getEntity());                    return result;                }                return null;            }        });        new Thread(task).start();        return task.get();    }}

服務端

public class BaseServlet extends HttpServlet{    private ApplicationContext ctx;    public void init(ServletConfig config)        throws ServletException    {        super.init(config);        // 擷取Web應用中的ApplicationContext執行個體        ctx = WebApplicationContextUtils            .getWebApplicationContext(getServletContext());    }    // 返回Web應用中的Spring容器    public ApplicationContext getCtx()    {        return this.ctx;    }}
@WebServlet(urlPatterns="/android/login.jsp")public class LoginServlet extends BaseServlet{    public void service(HttpServletRequest request ,        HttpServletResponse response)        throws IOException , ServletException    {        String user = request.getParameter("user");        String pass = request.getParameter("pass");        // 擷取系統的商務邏輯組件        AuctionManager auctionManager = (AuctionManager)getCtx().getBean("mgr");        // 驗證使用者登入        int userId = auctionManager.validLogin(user , pass);        response.setContentType("text/html; charset=GBK");        // 登入成功        if (userId > 0)        {            request.getSession(true).setAttribute("userId" , userId);        }        try        {            // 把驗證的userId封裝成JSONObject            JSONObject jsonObj = new JSONObject()                .put("userId" , userId);            // 輸出響應            response.getWriter().println(jsonObj.toString());        }        catch (JSONException ex)        {            ex.printStackTrace();        }    }}

 

Android HttpServlet Json 資料互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.