好长一段时间没有去写博客了,最近公司有新的需求,与服务器端交互采用与以往不同的交互方式,

  开发android的童鞋们都知道,一般用post或者get直接带参数到服务器,但是还有两种方式,在某些情况下使用比较频繁,当时就卡住了解决了很长一段时间,网上的教程说的都不太实用,现把自己的实际摸索出来的一套流程分享给大家。

  1.需要在http请求头中带参数传递给服务器

    比如:服务器需要在请求头中加入 Authorization,并且将用户的用户名和密码拼装成字符串传递过去,这样做的好处是比一般get请求更加的安全,

      具体实现为:

        1.1 利用java原生的HttpConnection即可实现,将Authorization和字符串当作配置设置进入即可

          



netUrl = new URL(path);
            conn = (HttpURLConnection) netUrl.openConnection();
            conn.setRequestProperty("Authorization", str);
            conn.setRequestMethod("GET");// 大写
            LogUtils.i("服务器返回码为==" + conn.getResponseCode());
            is = conn.getInputStream();
            String result = UIUtils.readStream(is);
            LogUtils.i("服务器返回值==" + result);
            Gson gson=new Gson();
            final LoginEntity entity = gson.fromJson(result, LoginEntity.class);
            UIUtils.getHandler().post(new Runnable() {
                @Override
                public void run() {
                    if (entity.result){
                        //说明登录成功
                        dismissProgressDialog();
                        start();
                        SharedPreferencesUtils.saveString("loginInfo",str);
                    }else{
                        UIUtils.showToastSafe("登录失败,请检查用户名或密码是否正确");
                        dismissProgressDialog();
                    }
                }
            });



      主要代码是其中的 conn.setRequestProperty("Authorization", str);其他的代码相信大家都耳熟能详!

 

  2.需要传递json字符串到服务器:

    最新的需求是,当客户填写一个表单数据时,由于表单数据很多,传统的post带参数并不适合此类场景,而客户端转化为json字符串后,将参数放到json中更为省流量

    实现步骤:

      这里我们用三种方式,传统的httpConnection Android的httpclient和开源框架xutils来实现

      原理最核心的是,一定要把传输类型设置为  application/json

      1.httpConnetion实现

        



URL url = null;
        try {
            JSONObject jsonObject = getJsonObject();
       .........//将需要的参数封装进jsonobject中

            url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时时间。
            conn.setConnectTimeout(30000);
            //区别2 : 请求方式 post
            conn.setRequestMethod("POST");// 大写
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
            //区别3: 必须指定两个请求的参数。
            conn.setRequestProperty("Content-Type", "application/json");//请求的类型 表单数据//区别4: 记得设置把数据写给服务器。
            conn.setDoOutput(true);//设置向服务器写数据。
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.getOutputStream().write(String.valueOf(jsonObject).getBytes());//把数据以流的方式写给服务器。
            int code = conn.getResponseCode();
            LogUtils.i("code==" + code);
            InputStream is = conn.getInputStream();
            String s = UIUtils.readStream(is);


            LogUtils.i("result==" + s);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.i("请求失败");
        }



      注意一定要设置请求类型 conn.setRequestProperty("Content-Type", "application/json"); 另外conn.setDoOutput(true)设置向服务器写数据也很重要。

 

   2.httpClient实现

      



//创建浏览器
            HttpClient client = new DefaultHttpClient();
            //输入地址
            HttpPost post = new HttpPost(path);
       ..........//将需要的参数封装进jsonObject中
            StringEntity se = new StringEntity(String.valueOf(getJsonObject()));
            se.setContentType("application/json");//表格采用的编码是utf-8
            post.setEntity(se);
            //敲回车
            LogUtils.i("正在请求==");
            HttpResponse response = client.execute(post);
            LogUtils.i("请求");
            int code = response.getStatusLine().getStatusCode();
            LogUtils.i("请求码=="+code);
            if (code == 201) {
                LogUtils.i("请求成功=="+code);

            } else {
                //请求失败
                LogUtils.i("请求失败=="+code);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.i("请求失败==" + e.getMessage());
        }



    由于对httpClient不是很熟,折腾了很久,主要是设置请求方式与一般不同,主要是这两句起作用



StringEntity se = new StringEntity(String.valueOf(getJsonObject()));
se.setContentType("application/json");



    3.最后来一个xutils框架实现的

         


new HttpUtils();
        RequestParams params = new RequestParams();
        params.setContentType("application/json");
    //把需要的参数封装进jsonObject中

        params.setBodyEntity(new StringEntity(String.valueOf(jsonObject)));
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                LogUtils.i("请求成功");
                LogUtils.i(responseInfo.result);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                LogUtils.i("请求失败");
                LogUtils.i(msg);
                LogUtils.i("code==" + error.getExceptionCode() + "");
            }
        });