安卓访问网络常用的3种方式(httpClient, httpUrlConnection,android-query ajax)及cookie处理

安卓常用的连接网络的方式:

1.HttpClient:

httpClient是最常用的,需要Apache的jar包

private static DefaultHttpClient httpClient = new DefaultHttpClient();

public static String cookie = null;

public static void get(Map<String, Object> pa, Context context, OnDateRecieceListener listener) {
    List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("参数名", "参数"));

    try {
        HttpPost postMethod = new HttpPost(ProjectSetting.baseUrl + "api/AddComment");
        postMethod.setHeader("Cookie", cookie); // 如果不需要cookie可以删掉

        postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        HttpResponse response = httpClient.execute(postMethod);
        String strResult = EntityUtils.toString(response.getEntity()).replace("\t","").replace("\n", "").replace("\r", "");
	// 如果是json可以这样处理
JSONObject json = new JSONObject(strResult); if (null != json) { } else { Toast.makeText(context, "连接网络失败,请检查网络", Toast.LENGTH_SHORT).show(); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(context, "数据错误", Toast.LENGTH_SHORT).show(); }}

2. HttpUrlConnection:

httpUrlConnection用得也比较多,简单方便


//cookie处理
public static String sCookie = "";

public static Object urlConnection(String url, String pa, Context context) {
    Object result = null;
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(ProjectSetting.baseUrl + url).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        
        // 不需要cookie可以删掉
        if (sCookie != null && !sCookie.isEmpty()) {
            conn.setRequestProperty("Cookie", sCookie);
        }

        // Send data
        PrintWriter pw = new PrintWriter(conn.getOutputStream());
        
        // pa为请求的参数
        pw.print(pa);
        pw.flush();
        pw.close();

        // Get the response!
        int httpResponseCode = conn.getResponseCode();
        if (httpResponseCode != HttpURLConnection.HTTP_OK) {
            throw new Exception("HTTP response code: " + httpResponseCode);
        }

        // inputStream为http返回的数据
        InputStream inputStream = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String response = "";
        String readLine;
        while (null != (readLine = br.readLine())) {
            response = response + readLine;
        }
        inputStream.close();

        // 如果为json可以这样处理
        if (!response.isEmpty()) {
            JSONObject json = JSON.parseObject(response.replace("\t", "").replace("\n", "").replace("\r", ""));
            
                result = json;
            
        } else {
            Toast.makeText(context, "连接网络失败,请检查网络", Toast.LENGTH_SHORT).show();
        }
        // 保存cookie
        String cookie = conn.getHeaderField("set-cookie");
        if (cookie != null && cookie.length() > 0) {
            sCookie = cookie;
        }
        conn.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

3.使用android-query框架

private static Context context;
private static AjaxCallback<JSONObject> callback = new AjaxCallback<JSONObject>() {
    @Override
    public void callback(String url, JSONObject json, AjaxStatus status) {
        List<Cookie> cookies = status.getCookies();
        for (Cookie cookie : cookies) {
            this.cookie(cookie.getName(), cookie.getValue());
        }
        if (json != null) {
            try {
                
            } catch (JSONException e) {
                Toast.makeText(context, "数据错误", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

        } else {
            Toast.makeText(context, "连接网络失败,请检查网络", Toast.LENGTH_SHORT).show();
        }
    }
};

public static void getData(String url, Context con, Map<String, Object> params, AQuery aQuery) {
    context = con;
    AbstractAjaxCallback.setReuseHttpClient(true);

    aQuery.ajax(url, params, JSONObject.class, callback);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值