Volley GET/POST请求的基本步骤:
1. 创建一个RequestQueue对象。
2. 创建一个 StringRequest/JsonObjectRequest/JsonArrayRequest 对象。
3. 将 StringRequest/JsonObjectRequest/JsonArrayRequest 对象添加到RequestQueue里面。
关于JsonObjectRequest的post请求,有时无法正确解析上传的参数,原因在于服务端不接收json请求方式,只接收字符串,即服务端接收字符串,返回json串,这时需改写JsonObjectRequest方法,详见volley_JsonObjectRequestPost2()。
直接上代码,使用说明见注释:
第一步 搭建环境
下载jar包,新建工程,导入volley.jar
第二步 AndroidManifest.xml 文件
打开网络权限 (<uses-permission android:name="android.permission.INTERNET" />)
引入MyApplication (android:name="com.example.volleyfrademo.MyApplication")
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.volleyfrademo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name="com.example.volleyfrademo.MyApplication">
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
第三步 MyApplication.java 文件
package com.example.volleyfrademo;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.Volley;
import android.app.Application;
import android.text.TextUtils;
public class MyApplication extends Application {
public static final String TAG = "MyApplication";
private RequestQueue queues;
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public