Android 实战之酷云(二)

对于酷云这个项目,想了很久,到底是做到最好,还是能用就好,在我看来,完成这个项目的难度还是有的,加上其他限制,导致进度缓慢,不过我觉得还是要将它呈现出来,所以决定写下酷云开发过程的一系列文章,希望能和大家一起进步。如果有更好的方法实现或者有错误,希望您在评论区能指出,我会及时更改。


Http Post 实现网络请求、数据提交

使用 Http 协议来对服务器接口进行请求,请求方式为 Post,请求方法包括 http请求头(cookie、referer)

protected boolean sendHttpPostRequest(String request) throws IOException {
        HttpURLConnection connection = null;
        try{
            String httpUrl = "http://music.163.com/api/search/pc/";
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            //设置http请求方法
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");//设置请求方式为post
            connection.setReadTimeout(5000);//设置读取超时为5秒
            connection.setConnectTimeout(10000);//设置连接超时为10秒
            //设置请求头,包括Cookie、refer、Charset
            connection.setRequestProperty("os", "pc");
            connection.setRequestProperty("MUSIC_U", "5339640232");
            connection.setRequestProperty("Charset", "utf-8");
            //进行连接
            connection.connect();
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            //请求参数
            String data = "&s=" + URLEncoder.encode(request, "UTF-8")+ "&limit=" + URLEncoder.encode("10", "UTF-8")+ "&type="
                    + URLEncoder.encode("1", "UTF-8") + "&offset" + URLEncoder.encode("0", "UTF-8") + "&total=" + URLEncoder.encode("true", "UTF-8");
            //通过EdirText获取输入内容进行搜索;因为手机屏幕原因,将搜索返回数目控制为10条;搜索形式为单曲搜索;偏移量设置为0,即不进行偏移

            //获取输出流
            out.writeBytes(data);
            out.flush();
            out.close();
            //获取响应输入流对象
            if (connection.getResponseCode() == 200) {
                InputStreamReader is = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(is);
                StringBuilder strBuffer = new StringBuilder();
                String line;
                //读取服务器返回信息
                while ((line = bufferedReader.readLine()) != null){
                    strBuffer.append(line);
                }
                result = strBuffer.toString();
                bufferedReader.close();
                is.close();
            }
        }catch (IOException e) {
            return true;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return false;
    }

以上通过 http post 方法进行网络请求并向服务器提交请求数据,代码注释已经解释得很清楚了,就不再多做解释。

因为 Android 4.0 以后要求必须在子线程中进行网络请求,所以我们在子线程中调用 Http 请求方法和耗时操作。

private void search(){
        fatherspoetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Handler handler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (msg.what == 1) {
                            //提示读取结果
                            Toast.makeText(SearchActivity.this, result, Toast.LENGTH_LONG).show();
                        }
                    }
                };
                new Thread() {
                    public void run() {
                        //请求网络
                        try {
                            sendHttpPostRequest(request);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Message m = new Message();
                        m.what = 1;
                        // 发送消息到Handler
                        handler.sendMessage(m);
                    }
                }.start();
            }
        });
    }

JSON 数据解析

接下来要做的就是解析服务器返回信息,一般返回的数据类型为 xml 或 json 格式,此处返回的为 json 格式,所以只讲解 json 的解析方式。

json 的解析方法有很多种,这里之讲解两种常用的,没错,就是 Java 官方提供的 org.json 和 Google 开源的 Gson 了。

首先要介绍一下 json 的数据格式,有 json 对象(JSONObject)和 json 数组(JSONArray),对于两者的区别,我们先来看一段 json 数据。

{ “t_id”: 64, “user_name”: “建新”, “user_number”: 13710675396, “user_cardid”: 639039431, “user_passwd”: “hhhhhh”,”user_money”: 9999999999}

那么很明显上面是一段仅由 json 对象构成的 json 数据,解析起来很方便,使用 JSONObject 解析的代码如下

public void parseJson(String json) throws JSONException {
        JSONObject jsonObject = new JSONObject(json);
        String password = jsonObject.getString("user_passwd");
        String nickName = jsonObject.getString("user_name");
        int tId= jsonObject.getInt("t_id");
        int cardId = jsonObject.getInt("user_cardid");
        int money = jsonOb
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值