android开发框架(一)HTTP通信

android开发中,通信相关技术包括 http、socket、Bluetooth、NFC、HeadSet、USB,本篇主要介绍Http请求方式

HTTP:超文本传输协议,是互联网上应用最为广泛的网络通信协议;
包括httpclient、httpConnection
客户端与服务器建立连接,客户端发送请求,服务器接收请求并返回信息,客户端处理信息;

1.两种主要的请求方式 Get和Post

Get与Post请求区别:

Post请求可以向服务器传送数据,而且数据放在HTML HEADER内一起传送到服务端URL地址,将数据绑定在httpPost对象中,数据对用户不可见。

而Get是把参数数据队列加到提交的URL中,值和表单内各个字段一一对应,
例如(https://www.baidu.com/s?wd=android

Get 传送的数据量较小,不能大于2KB。Post传送的数据量较大,一般被默认为不受限制。
get安全性非常低,post安全性较高。

2.两种请求代码实现

Post请求

    public String httpPost(String url,ArrayList<Param> params){
        String response=null;
        int timeoutConncetion=2000;
        int timeoutSocket=2000;
        HttpParams httpParams=new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConncetion);
        HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);  
        HttpPost httpPost=new HttpPost(url);

        Log.i("url", url);
        if(params!=null){
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(list(params),HTTP.UTF_8));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            HttpResponse httpResponse=  httpClient.execute(httpPost);

            int resStatus=httpResponse.getStatusLine().getStatusCode();
            System.out.println(resStatus);
            if(resStatus==HttpStatus.SC_OK){
                //获得cookie
                //getCookie(httpClient);
                response=EntityUtils.toString(httpResponse.getEntity());

            }else{
                return response;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }



public List<NameValuePair> list(ArrayList<Param> params){
        ArrayList<NameValuePair> list=new ArrayList<NameValuePair>();
        for(Param p:params){
            NameValuePair pair=new BasicNameValuePair(p.getName(),p.getValue());
            list.add(pair);
        }
        return list;
    }

Get请求

public String httpGet(String url,ArrayList<Param> params){
        String response = null;
        StringBuffer urlstr=new StringBuffer(url);
        if(params!=null){
            urlstr.append("?");
            for(Param p:params){
                urlstr.append(p.getName()+"=").append(p.getValue()+"&");
            }
            urlstr.deleteCharAt(urlstr.length()-1);
        }
        String urlcon=urlstr.toString();
        System.out.println(urlcon);
        int timeoutConnection=15000;
        int timeoutSocket=15000;
        HttpParams httpParams=new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);   
        HttpGet httpGet=new HttpGet(urlcon);
        //添加cookie到http请求中
        //httpGet.setHeader("Cookie", Utils.getPreference("cookie"));
        try {
            httpClient = new DefaultHttpClient(httpParams);
            HttpResponse httpResponse=httpClient.execute(httpGet);  
            int resStatus=httpResponse.getStatusLine().getStatusCode();
            if(resStatus==HttpStatus.SC_OK){
                //getCookie(httpClient);
                //将返回数据转成字符串类型
                response=EntityUtils.toString(httpResponse.getEntity(),"UTF_8");

            }else{
                response="返回码为:"+resStatus;
            }
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

3.Cookie使用
当在Android客户端发送请求时,需要使用到Cookie用来维持用户登录状态

通常是在发送登录请求时获取cookie并通过sharedpreferences进行保存,在其他请求时

通过setHeader的方式加入到http中。

获取Cookie代码

    public void getCookie(DefaultHttpClient httpClient) {
         List<Cookie> cookies = httpClient.getCookieStore().getCookies();
         StringBuffer sb = new StringBuffer();
        for (int i = 0; i < cookies.size(); i++) {
             Cookie cookie = cookies.get(i);
             String cookieName = cookie.getName();
             String cookieValue = cookie.getValue();
            if (!TextUtils.isEmpty(cookieName)
                    && !TextUtils.isEmpty(cookieValue)) {
                sb.append(cookieName + "=");
                sb.append(cookieValue + ";");
            }
        }
        Log.e("cookie", sb.toString());
        System.out.println(MyApp.mContext);
        System.out.println(sb.toString());
        savePreference("cookie", sb.toString());
    }

保存和获取cookie的代码实例:

/**
     * 保存数据到sp
     * @param key
     * @param value
     */
    public static void savePreference(String key, String value) {
        PreferenceManager.getDefaultSharedPreferences(MyApp.mContext).edit().putString(key, value).commit();
    }


    /**
     * 从sp中取数据
     * @param mContext
     * @param key
     * @return
     */
    public static String getPreference(String key) {
        return PreferenceManager.getDefaultSharedPreferences(MyApp.mContext).getString(key, "");
    }

MyApp类继承Application,并在AndroidManifest中注册

public class MyApp extends Application {


    public static Context mContext = null;

    @Override  
    public void onCreate() {  
        super.onCreate();  
        mContext=getApplicationContext();
   }
}

当客户端需要进行网络请求服务时可以结合请求方式,进行使用。

未完待续。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值