下载jar包,新建工程,导入volley.jar
打开网络权限 (
引入MyApplication (android:name="com.example.volleyfrademo.MyApplication")
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 static synchronized MyApplication getInstance() {
return instance;
}
public RequestQueue getRequestQueue(){
if (queues == null) {
queues = Volley.newRequestQueue(getApplicationContext());
}
return queues;
}
public void addToRequestQueue(Request req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
VolleyLog.d("Adding request to queue: %s", req.getUrl());
getRequestQueue().add(req);
}
public void addToRequestQueue(Request req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (queues != null) {
queues.cancelAll(tag);
}
}
}
package com.example.volleyfrademo;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* Volley GET/POST请求的基本步骤:
* 1. 创建一个RequestQueue对象。
* 2. 创建一个 StringRequest/JsonObjectRequest/JsonArrayRequest 对象。
* 3. 将 StringRequest/JsonObjectRequest/JsonArrayRequest 对象添加到RequestQueue里面。
*
* @author jiatao
*/
public class MainActivity extends Activity implements OnClickListener{
private TextView tv_resp1;
private Button btn_get_string, btn_post_string, btn_get_jsonobject, btn_post_jsonobject, btn_post_jsonobject2, btn_get_jsonarray;
private String urlget = "http://gc.ditu.aliyun.com/geocoding?a=苏州市";
private String urlpost = "http://api.24ht.net/app/signin";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setEvent();
}
private void initView() {
tv_resp1 = (TextView) findViewById(R.id.tv_resp1);
btn_get_string = (Button) findViewById(R.id.btn_get_string);
btn_post_string = (Button) findViewById(R.id.btn_post_string);
btn_get_jsonobject = (Button) findViewById(R.id.btn_get_jsonobject);
btn_post_jsonobject = (Button) findViewById(R.id.btn_post_jsonobject);
btn_post_jsonobject2 = (Button) findViewById(R.id.btn_post_jsonobject2);
btn_get_jsonarray = (Button) findViewById(R.id.btn_get_jsonarray);
}
private void setEvent() {
btn_get_string.setOnClickListener(this);
btn_post_string.setOnClickListener(this);
btn_get_jsonobject.setOnClickListener(this);
btn_post_jsonobject.setOnClickListener(this);
btn_post_jsonobject2.setOnClickListener(this);
btn_get_jsonarray.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_get_string:
volley_StringRequestGet();
break;
case R.id.btn_post_string:
volley_StringRequestGetPost();
break;
case R.id.btn_get_jsonobject:
volley_JsonObjectRequestGet();
break;
case R.id.btn_post_jsonobject:
volley_JsonObjectRequestPost();
break;
case R.id.btn_post_jsonobject2:
volley_JsonObjectRequestPost2();
break;
case R.id.btn_get_jsonarray:
volley_JsonArrayRequestGet();
break;
}
}
/*
* StringRequest
* StringRequest — To retrieve response body as String (ideally if you intend to parse the response by yourself)
* 这个类可以用来从服务器获取String,如果想自己解析请求响应可以使用这个类,例如返回xml数据。它还可以使用重载的构造函数定制请求.
*
* GET方式请求服务器
*/
private void volley_StringRequestGet() {
StringRequest request = new StringRequest(Method.GET, urlget, new Listener() {
@Override
public void onResponse(String response) {
tv_resp1.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
});
request.setTag("volley_StringRequestGet");
MyApplication.getInstance().addToRequestQueue(request);
}
/*
* StringRequest
* StringRequest — To retrieve response body as String (ideally if you intend to parse the response by yourself)
* 这个类可以用来从服务器获取String,如果想自己解析请求响应可以使用这个类,例如返回xml数据。它还可以使用重载的构造函数定制请求.
*
* POST方式请求服务器
*/
private void volley_StringRequestGetPost() {
StringRequest request = new StringRequest(Method.POST, urlpost, new Listener() {
@Override
public void onResponse(String response) {
tv_resp1.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
}){
@Override
protected Map getParams() throws AuthFailureError {
Map map = new HashMap();
map.put("user", "jt1024");
map.put("psw", "111111");
return map;
}
};
request.setTag("volley_StringRequestGetPost");
MyApplication.getInstance().addToRequestQueue(request);
}
/*
* JsonObjectRequest
* JsonObjectRequest — To send and receive JSON Object from the Server
* 这个类可以用来发送和接收JSON对象。
* 这个类的一个重载构造函数允许设置适当的请求方法(DELETE,GET,POST和PUT)。
*
* GET方式请求服务器
*/
private void volley_JsonObjectRequestGet() {
JsonObjectRequest request = new JsonObjectRequest(Method.GET, urlget, null, new Listener() {
@Override
public void onResponse(JSONObject response) {
tv_resp1.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
});
request.setTag("volley_JsonObjectRequestGet");
MyApplication.getInstance().addToRequestQueue(request);
}
/*
* JsonObjectRequest
* JsonObjectRequest — To send and receive JSON Object from the Server
* 这个类可以用来发送和接收JSON对象。
* 这个类的一个重载构造函数允许设置适当的请求方法(DELETE,GET,POST和PUT)。
*
* POST方式请求服务器
*/
private void volley_JsonObjectRequestPost() {
Map map = new HashMap();
map.put("user", "jt1024");
map.put("psw", "111111");
JSONObject object = new JSONObject(map);
JsonObjectRequest request = new JsonObjectRequest(Method.POST, urlpost, object, new Listener() {
@Override
public void onResponse(JSONObject response) {
tv_resp1.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
});
request.setTag("volley_JsonObjectRequestPost");
MyApplication.getInstance().addToRequestQueue(request);
}
/*
* JsonObjectRequest
* 如果服务端并不支持json的请求方式,比如常见的spring mvc服务端,就很难支持json的请求方式,
* 那么就需要客户端以普通的post方式进行提交,服务端返回json串
* 首先在Activity类里,继承Request实现一个NormalPostRequest类
*
* 服务端不支持json的请求方式
*/
private void volley_JsonObjectRequestPost2() {
String url = "http://api.24ht.net/app/signin";
Map map = new HashMap();
map.put("user", "jt1024");
map.put("psw", "111111");
JSONObject object = new JSONObject(map);
NormalPostRequest request = new NormalPostRequest(url, map, new Listener() {
@Override
public void onResponse(JSONObject response) {
tv_resp1.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
});
request.setTag("volley_JsonObjectRequestPost2");
MyApplication.getInstance().addToRequestQueue(request);
}
private void volley_JsonArrayRequestGet() {
JsonArrayRequest request = new JsonArrayRequest(urlget, new Listener() {
@Override
public void onResponse(JSONArray response) {
tv_resp1.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
});
request.setTag("volley_JsonArrayRequestGet");
MyApplication.getInstance().addToRequestQueue(request);
}
}
package com.example.volleyfrademo;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
/**
*
* 对应MainActivity.java中的JsonObjectRequest-POST2:
* 如果服务端并不支持json的请求方式,比如常见的spring mvc服务端,就很难支持json的请求方式,
* 那么就需要客户端以普通的post方式进行提交,服务端返回json串
* 首先在Activity类里,继承Request实现一个NormalPostRequest类
*
* @author jiatao
*
*/
public class NormalPostRequest extends Request{
private Map mMap;
private Listener mListener;
public NormalPostRequest(String url, Map map, Listener listener,ErrorListener errorListener) {
super(Request.Method.POST, url, errorListener);
mListener = listener;
mMap = map;
}
//mMap是已经按照前面的方式,设置了参数的实例
@Override
protected Map getParams() throws AuthFailureError {
return mMap;
}
//此处因为response返回值需要json数据,和JsonObjectRequest类一样即可
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
}