Google官方网络框架-Volley的使用解析Json以及加载网络图片方法

简介: <div class="markdown_views"><h1 id="google官方网络框架-volley的使用解析json以及加载网络图片方法">Google官方网络框架-Volley的使用解析Json以及加载网络图片方法</h1><hr><pre><code> Volley是什么? Google I/O 大会上,Google 推出 Volley的一个网络框架

Google官方网络框架-Volley的使用解析Json以及加载网络图片方法


 Volley是什么?
 Google I/O 大会上,Google 推出 Volley的一个网络框架
 Volley适合什么场景?
 Volley适合网络通信频繁操作,并能同时实现多个网络通信。 

下载地址:http://download.csdn.net/detail/qq_26787115/9358787

1.Volley的使用解析Json

我们不罗嗦,直接开讲:

我们的需求很简单,就是做一个归属地查询的小软件,使用Volley解析一段地址获取Json并且解析Json显示出来,很简单的需求吧,也很基础,不过却很直观!
先来看看效果图吧!

号码是乱打的

步骤

1.申请地址已经key
2.把Volley的jar文件导入工程
3.解析地址获取到json
4.解析json填入

1.申请的Key:22a6ba14995ce26dd0002216be51dabb
2.接口地址(聚合数据申请的):http://apis.juhe.cn/mobile/get?phone=13429667914&key=您申请的KEY
3.将Volley导入工程
4.开工了

注意一定要先添加权限:<uses-permission android:name="android.permission.INTERNET"/>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/tab1_rl"
        android:layout_width="match_parent"
        android:layout_height="51dp"
        android:background="#34c083" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="51dp"
            android:layout_centerHorizontal="true"
            android:background="@null"
            android:gravity="center"
            android:text="归属地查询"
            android:textColor="@android:color/white"
            android:textSize="20dp" />
    </RelativeLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:text="请输入你的手机号码查询归属地信息" />

    <EditText
        android:id="@+id/et"
        android:layout_width="fill_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="@drawable/ed_bg"
        android:gravity="center"
        android:hint="请输入正确的电话号码" />

    <Button
        android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="#34c083"
        android:text="查询"
        android:textColor="@android:color/white" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_marginTop="10dp"
        android:background="#aeaea9" />

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:gravity="center_vertical"
        android:text="归属地:" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#aeaea9" />

    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:gravity="center_vertical"
        android:text="区号:" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#aeaea9" />

    <TextView
        android:id="@+id/tv3"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:gravity="center_vertical"
        android:text="运营商:" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#aeaea9" />

    <TextView
        android:id="@+id/tv4"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:gravity="center_vertical"
        android:text="用户类型:" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#aeaea9" />

</LinearLayout>
这里没什么可说的,和预览界面的布局是一样的
EditText:输入电话号码 id: android:id="@+id/et"
Button:点击查询  android:id="@+id/btn"
TextView:归属地,区号,运营商,用户类型   android:id="@+id/tv1234"

MainActivity.java

这里首先说一下步骤了:
1.初始化这几个控件
2.给Button添加点击事件
//这里就是判断用户输入的方法,输入不为空的话就执行 Volley_Get();方法
btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                myPhone = et.getText().toString();
                if (et == null) {
                    Toast.makeText(MainActivity.this, "号码不能为空",
                            Toast.LENGTH_LONG).show();
                } else {
                    Volley_Get();
                }
            }
        });
3.Volley_Get方法是解析接口获取Json字符的,并且使用的是GET方法,还有POST方法我就不赘述了,抛砖引玉,不懂自行Google
    private void Volley_Get() {
        //接口地址 myphone为我们输入的电话号码  Key:22a6ba14995ce26dd0002216be51dabb
        String url = "http://apis.juhe.cn/mobile/get?phone=" + myPhone
                + "&key=22a6ba14995ce26dd0002216be51dabb";
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest request = new StringRequest(Method.GET, url,
                new Listener<String>() {
                    // 成功
                    @Override
                    public void onResponse(String json) {
                        Volley_Json(json);
                        Toast.makeText(MainActivity.this, "成功:"+json, 1).show();
                    }
                }, new Response.ErrorListener() {
                    // 失败
                    @Override
                    public void onErrorResponse(VolleyError errorLog) {
                        Toast.makeText(MainActivity.this, "失败:"+errorLog.toString(),
                                Toast.LENGTH_LONG).show();
                    }
                });
        queue.add(request);

    }

4.Volley_Json();

当我们解析这个接口成功的话就会得到一个json的字符串了,具体的样子是这个样子的
    {
    "resultcode": "200",
    "reason": "Return Successd!",
    "result": {
        "province": "江西",
        "city": "吉安",
        "areacode": "0796",
        "zip": "343000",
        "company": "中国联通",
        "card": "江西联通GSM卡"
    },
    "error_code": 0
}
我们现在新建一个方法Volley_Json()并且定义一个String的参数,如下:
private void Volley_Json(String json) {
        //result为200说明成功
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONObject object = jsonObject.getJSONObject("result");
            tv1.setText("归属地:" + object.getString("province") + "-"
                    + object.getString("city"));
            tv2.setText("区号:" + object.getString("areacode"));
            tv3.setText("运营商:" + object.getString("company"));
            tv4.setText("用户类型:" + object.getString("card"));

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

这样子就可以解析出json中的字符串并且显示出来达到归属地的查询效果了,下面是MainActivity的完整代码以及Demo下载链接:

package com.lgl.queryaddress;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends Activity {

    private TextView tv1, tv2, tv3, tv4;
    private EditText et;
    private Button btn;
    private String myPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        getActionBar().hide();
        setContentView(R.layout.activity_main);

        initView();
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                myPhone = et.getText().toString();
                if (et == null) {
                    Toast.makeText(MainActivity.this, "号码不能为空",
                            Toast.LENGTH_LONG).show();
                } else {
                    Volley_Get();
                }
            }
        });
    }

    private void initView() {
        et = (EditText) findViewById(R.id.et);
        btn = (Button) findViewById(R.id.btn);
        tv1 = (TextView) findViewById(R.id.tv1);
        tv2 = (TextView) findViewById(R.id.tv2);
        tv3 = (TextView) findViewById(R.id.tv3);
        tv4 = (TextView) findViewById(R.id.tv4);
    }

    private void Volley_Get() {
        String url = "http://apis.juhe.cn/mobile/get?phone=" + myPhone
                + "&key=22a6ba14995ce26dd0002216be51dabb";
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest request = new StringRequest(Method.GET, url,
                new Listener<String>() {
                    // 成功
                    @Override
                    public void onResponse(String json) {
                        Volley_Json(json);
                        Toast.makeText(MainActivity.this, "成功:"+json, 1).show();
                    }
                }, new Response.ErrorListener() {
                    // 失败
                    @Override
                    public void onErrorResponse(VolleyError errorLog) {
                        Toast.makeText(MainActivity.this, "失败:"+errorLog.toString(),
                                Toast.LENGTH_LONG).show();
                    }
                });
        queue.add(request);

    }

    private void Volley_Json(String json) {
        //result为200说明成功
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONObject object = jsonObject.getJSONObject("result");
            tv1.setText("归属地:" + object.getString("province") + "-"
                    + object.getString("city"));
            tv2.setText("区号:" + object.getString("areacode"));
            tv3.setText("运营商:" + object.getString("company"));
            tv4.setText("用户类型:" + object.getString("card"));

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Demo下载地址:http://download.csdn.net/detail/qq_26787115/9360953

2.Volley加载网络图片

 相对于请求json字符串,解析网络的图片倒是步骤少了,玩法也多起来,我们还是从简单的做起,还是以一个例子来,先看下效果图!

刘桂林

就是一个Button和一个ImageView,点击Button加载图片信息

步骤
1.获取图片的链接
2.添加权限
3.加载网络图片

layout_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:background="#FDFDFD">

    <RelativeLayout
        android:id="@+id/tab1_rl"
        android:layout_width="match_parent"
        android:layout_height="51dp"
        android:background="#34c083" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="51dp"
            android:layout_centerHorizontal="true"
            android:background="@null"
            android:gravity="center"
            android:text="归属地查询"
            android:textColor="@android:color/white"
            android:textSize="20dp" />
    </RelativeLayout>

    <Button
        android:id="@+id/btn"
        android:textSize="20sp"
        android:textColor="@android:color/white"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="30dp"
        android:background="#34c083"
        android:text="加载图片" />

    <ImageView
        android:layout_marginTop="50dp"
        android:layout_gravity="center_horizontal"
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>
一个Button  android:id="@+id/btn"
一个imageview  android:id="@+id/iv"

初始化这两个控件之后就直接解析了,代码不多,看MainActivity的完整代码

package com.lglvolleyiv;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private Button btn;
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().hide();
        setContentView(R.layout.activity_main);

        iv = (ImageView) findViewById(R.id.iv);
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Volley_Iv();
            }
        });

    }

    // 加载图片
    protected void Volley_Iv() {
        //图片是百度的logo,直接浏览器右键获取图片地址即可
        String url ="http://ss.bdimg.com/static/superman/img/logo/bd_logo1_31bdc765.png";
        //请求
        RequestQueue queue = Volley.newRequestQueue(this);
         /**
          * ImageRequest的构造函数接收六个参数,
          * 第一个参数就是图片的URL地址。
          * 第二个参数是图片请求成功的回调,这里我们把返回的Bitmap参数设置到ImageView中。
          * 第三第四个参数分别用于指定允许图片最大的宽度和高度,设置不正确会对图片进行压缩。
          * 第五个参数用于指定图片的颜色属性,Bitmap.Config下的几个常量都可以在这里使用。
          * 第六个参数是图片请求失败的回调,这里我们当请求失败时在ImageView中显示一张默认图片。
          */
         ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {

            @Override
            public void onResponse(Bitmap response) {
                //成功就直接设置获取到的bitmap图片
                iv.setImageBitmap(response);
            }
        }, 0, 0, Config.RGB_565, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // 失败了
            }
        });
        //最后将这个ImageRequest对象添加到RequestQueue里就可以
        queue.add(imageRequest);
    }
}

Demo下载地址:http://download.csdn.net/detail/qq_26787115/9362615

这个项目的完整思路应该是查询到了运营商显示相应的logo,不过这部分还没做,完善了整个项目的构架就上架了,有兴趣的可以去试试:


百度:http://shouji.baidu.com/software/item?docid=8424313&from=as

91:http://apk.91.com/Soft/Android/com.lgl.queryaddress-1.html

安卓:http://apk.hiapk.com/appinfo/com.lgl.queryaddress/1


上线项目的源码:http://download.csdn.net/detail/qq_26787115/9379019

后续还会继续更新一些,这只是抛砖引玉写一些基础而已,高手勿喷!!!

目录
相关文章
|
15天前
|
JSON JavaScript 前端开发
JavaScript原生代码处理JSON的一些高频次方法合集
JavaScript原生代码处理JSON的一些高频次方法合集
|
29天前
|
机器学习/深度学习 算法 PyTorch
RPN(Region Proposal Networks)候选区域网络算法解析(附PyTorch代码)
RPN(Region Proposal Networks)候选区域网络算法解析(附PyTorch代码)
213 1
|
1月前
|
缓存 网络协议 Linux
【Shell 命令集合 网络通讯 】Linux 配置DNS dnsconf 命令 使用教程
【Shell 命令集合 网络通讯 】Linux 配置DNS dnsconf 命令 使用教程
38 0
|
29天前
|
JSON JavaScript 前端开发
C++ 智能指针与 JSON 处理:高级编程技巧与常见问题解析
C++ 智能指针与 JSON 处理:高级编程技巧与常见问题解析
264 0
|
10天前
|
SQL API 数据库
Python中的SQLAlchemy框架:深度解析与实战应用
【4月更文挑战第13天】在Python的众多ORM(对象关系映射)框架中,SQLAlchemy以其功能强大、灵活性和易扩展性脱颖而出,成为许多开发者首选的数据库操作工具。本文将深入探讨SQLAlchemy的核心概念、功能特点以及实战应用,帮助读者更好地理解和使用这一框架。
|
11天前
|
存储 JSON JavaScript
「Python系列」Python JSON数据解析
在Python中解析JSON数据通常使用`json`模块。`json`模块提供了将JSON格式的数据转换为Python对象(如列表、字典等)以及将Python对象转换为JSON格式的数据的方法。
27 0
|
11天前
|
机器学习/深度学习 分布式计算 BI
Flink实时流处理框架原理与应用:面试经验与必备知识点解析
【4月更文挑战第9天】本文详尽探讨了Flink实时流处理框架的原理,包括运行时架构、数据流模型、状态管理和容错机制、资源调度与优化以及与外部系统的集成。此外,还介绍了Flink在实时数据管道、分析、数仓与BI、机器学习等领域的应用实践。同时,文章提供了面试经验与常见问题解析,如Flink与其他系统的对比、实际项目挑战及解决方案,并展望了Flink的未来发展趋势。附带Java DataStream API代码样例,为学习和面试准备提供了实用素材。
33 0
|
12天前
|
存储 安全 测试技术
网络奇谭:虚拟机中的共享、桥接与Host-Only模式解析
网络奇谭:虚拟机中的共享、桥接与Host-Only模式解析
18 0
|
29天前
|
JSON JavaScript 数据格式
【深入探究C++ JSON库】解析JSON元素的层级管理与遍历手段
【深入探究C++ JSON库】解析JSON元素的层级管理与遍历手段
86 2
|
29天前
|
机器学习/深度学习 存储 供应链
【软件设计师备考 专题 】运算基本方法:预测与决策、线性规划、网络图、模拟
【软件设计师备考 专题 】运算基本方法:预测与决策、线性规划、网络图、模拟
57 0

推荐镜像

更多