今天学习使用了网络请求库Volley。
在这里以聚合数据的天气预报API为例子来看看Volley库是怎么获取数据的,大家首先要获取相应API的Key,聚合数据都有文档。
首先在app下的build.gradle中配置远程库,这一点相信用过Android Studio的都会,如下:
compile 'com.android.volley:volley:1.0.0'
然后是主界面,url从聚合数据来获取,后面填上自己申请的Key,这里的RequestQueue和JsonObjectRequest都是Volley库提供的对象,Volley也还有其他对象,在这里不细讲啦,大家可以自己研究,以下是Demo:
/**
* 主界面
*
* @author yuzhentao
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button_activity_main).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getJson();
}
});
}
private void getJson() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "http://op.juhe.cn/onebox/weather/query?cityname=%E6%B8%A9%E5%B7%9E&key=这里是KEY";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, "获取成功=" + response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "获取失败=" + error, Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
效果图:
Demo地址:http://download.youkuaiyun.com/detail/qq_23940659/9467101