android 之httpclient方式提交数据

HttpClient:

 今天实战下httpclient请求网络json数据,解析json数据返回信息,显示在textview,

起因:学校查询饭卡余额,每次都要访问校园网(内网),才可以查询,然后才是登录学校查询饭卡的网站查,

有木有很麻烦,今天我来测试下,正好学到httpclient请求网络数据,用httpclient来请求数据,查询饭卡余额

1:先是用fiddler截包,获取网络请求参数,第一步先是要用Student账号登录校园网,通过分析得到post请求用户名没有加密,密码是加密后的密码

POST http://ip/ HTTP/1.1
Host: ip
Connection: keep-alive
Content-Length: 95
Cache-Control: max-age=0
Origin: http://ip
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: http://ip/
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.8

DDDDD=学号&upass=加密后的字符串&R1=0&R2=1&para=00&0MKKey=打码

2:第二步是访问饭卡查询网,截包分析这里,XSP000学号,分析得到获取json数据只要下面的GET请求就可以了,

GET http://ip2/web/SystemListener?className=cn.com.system.query.DealQuery&methodName=getDealInfo&paramCount=1&param_0=XSP000学号&_dc=1482242227206 HTTP/1.1
Host: ip2
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
X-Requested-With: XMLHttpRequest
Accept: */*
Referer: http://ip2/web/main.jsp
Accept-Encoding: gzip, deflate, sdch
Accept-Language: zh-CN,zh;q=0.8
Cookie: JSESSIONID=xxxxxxxxxxxxxxxxxxx; JSESSIONID=xxxxxxxxxxxxxxxxxxxxxxxxxxxx

返回的json信息

[
{"status":"0","name":"用户编号","info":"打码"},
{"status":"0","name":"用户姓名","info":"打码"},
{"status":"0","name":"帐号信息","info":"打码"},
{"status":"0","name":"卡号","info":"打码"},
{"status":"0","name":"所属机构","info":"打码"},
{"status":"1","name":"卡状态","info":"正常"},
{"status":"0","name":"用户类型","info":"学生"},
{"status":"0","name":"账户金额","info":"28元"},
{"status":"0","name":"脱机消费总额","info":"0元"},
{"status":"0","name":"登录日期","info":"2016年12月20日 星期二"}
]

第三步:实战操作,

3.1界面布局

3.2 在手机端用学生账号连接校园网,当打开这个程序的时候,程序自动登录校园网,程序是先执行OnCreate加载界面这时界面还没有呈现给用户,在Onstart()函数执行完数据初始化,这时就要post登录校园网写在OnStart()里面初始化数据,执行完onStart()函数后,界面才程序给用户,当成功登录后,登录手机端程序的时候就弹窗成功登录

(根据登录校园网成功后返回  <title>登录成功</title>信息)

Onstart里面的主要代码:

protected void onStart() {
        super.onStart();
        final Handler handler1 = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    //登录成功弹窗:成功登录,失败:提示返回信息
                    Toast.makeText(getApplicationContext(), msg.getData().getString("info"), Toast.LENGTH_SHORT).show();
                }
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result_login = LoginHttpUtil.requestNetForPost("学号", "密码加密后的字符串");
                String regex = "<title>(.*?)</title>";
                Pattern p = Pattern.compile(regex);
                Matcher m = p.matcher(result_login);
                while (m.find()) {
                    String str = m.group(1);
                    Message msg = Message.obtain();
                    Bundle data = new Bundle();
                    data.putString("info", str);
                    msg.setData(data);
                    msg.what = 1;
                    handler1.sendMessage(msg);
                }
            }
        }).start();
    }

3.3 然后输入用户和密码,这里密码可用不用输入,GET请求里面没有用到password,可怕,学校太渣了-><-

在onCreate里面按钮点击事件写一个登录饭卡网函数

//饭卡查询结果
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 2) {
                String name = msg.getData().getString("name");
                String yue = msg.getData().getString("yue");
                String institution = msg.getData().getString("institution");
                String datetime = msg.getData().getString("datetime");
                ca_showname.setText(name);
                ca_showmoney.setText(yue);
                ca_institution.setText(institution);
                ca_time.setText(datetime);
            }
        }
    };

    public void loginCard() {
        final String username = ed_ca_username.getText().toString();
        final String password = ed_ca_password.getText().toString();
        //判断是否密码或者用户名为空
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(getApplication(), "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        //post方法登录饭卡查询网是否成功
        LoginHttpUtil.requestNetFromMealCard(handler, username);
        //  System.out.println("================是否登录学校网:"+result);
    }

新建一个包,里面新建一个类,写网络请求的操作

public class LoginHttpUtil {

    //登录校园网的操作
    public static String requestNetForPost(final String username, final String password) {

        // 根据url获得HttpPost对象
        HttpPost httpRequest = new HttpPost("http://ip1");
        // 取得默认的HttpClient
        DefaultHttpClient httpclient = new DefaultHttpClient();
        String strResult = null;
        // NameValuePair实现请求参数的封装
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("DDDDD", username));
        params.add(new BasicNameValuePair("upass", password));
        params.add(new BasicNameValuePair("R1", "0"));
        params.add(new BasicNameValuePair("R2", "1"));
        params.add(new BasicNameValuePair("para", "00"));
        params.add(new BasicNameValuePair("0MKKey", "打码"));

        httpRequest.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");
        httpRequest.addHeader("Origin", "ip1");
        httpRequest.addHeader("Referer", "ip1");
        httpRequest.addHeader("Upgrade-Insecure-Requests", "1");
        httpRequest.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");

        try {
            // 添加请求参数到请求对象
            httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            // 获得响应对象
            HttpResponse httpResponse = httpclient.execute(httpRequest);
            // 判断是否请求成功
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                //转换为gb2312
                strResult = EntityUtils.toString(httpResponse.getEntity(), "gb2312");
            } else {
                strResult = "错误响应:" + httpResponse.getStatusLine().toString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strResult;
    }

    //get方式登录饭卡网
    public static void requestNetFromMealCard(final Handler handler, final String username) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String url="http://ip2/SystemListener?className=cn.com.system.query.DealQuery&methodName=getDealInfo&paramCount=1&param_0=XSP000"+username;
                //httpGet对象
                HttpGet httpGet = new HttpGet(url);
                DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
                String JsonResult=null;
                try {
                    HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
                    if(httpResponse.getStatusLine().getStatusCode()==200){
                        //返回的信息转为json字符串数组
                        JsonResult=EntityUtils.toString(httpResponse.getEntity());
                        JSONArray array=new JSONArray(JsonResult);
                        //System.out.println("=============饭卡信息:"+array);

                        String yue = array.getString(7);//根据索引得到索引位置7的余额,索引从0开始
                        JSONObject yue1=new JSONObject(yue);
                        String yue2 = yue1.getString("info");

                        String name = array.getString(1);
                        JSONObject name1=new JSONObject(name);
                        String name2 = name1.getString("info");//用户姓名

                        String institution = array.getString(4);  //所属机构institution
                        JSONObject institution1=new JSONObject(institution);
                        String institution2 = institution1.getString("info");

                        String datetime = array.getString(9);  //登录日期
                        JSONObject datetime1=new JSONObject(datetime);
                        String datetime2 = datetime1.getString("info");

                        Message msg= Message.obtain();
                        msg.what=2;
                        Bundle data = new Bundle();
                        data.putString("name",name2);
                        data.putString("yue",yue2);
                        data.putString("institution",institution2);
                        data.putString("datetime",datetime2);
//                        System.out.println("--------handler传递的值:"+data);
                        msg.setData(data);
                        handler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}

收工,可怕,这个月饭卡只有这一点点了,我要去充值了

 

原文地址:https://www.cnblogs.com/DonAndy/p/6196095.html