Volley可是说是把AsyncHttpClient和Universal-Image-Loader的优点集于了一身,既可以像AsyncHttpClient一样非常简单地进行HTTP通信,也可以像Universal-Image-Loader一样轻松加载网络上的图片。除了简单易用之外,Volley在性能方面也进行了大幅度的调整,它的设计目标就是非常适合去进行数据量不大,但通信频繁的网络操作。
但是,需要注意的是,对于大数据量的网络操作,比如说下载文件等,一般都不推荐使用volley框架。
导入volley包
第一步,实例化RequestQueue
请求队列的创建可以有两种模式:
1、
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
2、这边官方推荐的方式是单例模式创建请求,这样会避免不必要的内存浪费。
RequestQueue mQueue = Volley.newRequestQueue(context);
第二步,新建一个Request
1)StringRequest
@参数method 网络请求方式(Get, Post等,一般采用post方式)
@参数url 网络请求地址
@参数listener 成功后的处理
@参数errorListener 失败后的处理
如果需要传递传递参数,需要重写getParams方法。
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String, String> getParams()
throws AuthFailureError {
Map<String,String> map=new HashMap<String, String>();
map.put("username", "小明");
map.put("userpwd", "123");
return map;
}
};
2)JsonObjectRequest
@参数method 网络请求方式(Get, Post等)
@参数url 网络请求地址
@参数jsonRequest 请求参数
@参数listener 成功后的处理
@参数errorListener 失败后的处理
注意:在使用JsonObjectRequest时,由网络传来的值,只能是Json解析后的内容,不可以添加其他的东西,
例如:返回结果为{"username":"小明","userage":"23","usersex":"男"}是正确的,而返回结果为post验证通过{"username":"小明","userage":"23","usersex":"男"}是错误的,因为多了“post验证通过”,使返回的不属于JSONObject
Get方法:
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url+"?username="+str+"&userpwd=123", null,new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String name=response.getString("username");
int age=Integer.parseInt(response.getString("userage"));
String sex=response.getString("usersex");
Toast.makeText(MainActivity.this, name+","+age+","+sex, Toast.LENGTH_SHORT).show();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
}
});
Post方法:新建一个工具类
package com.example.util;
import java.io.UnsupportedEncodingException;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
public class MyJsonObjectRequest extends JsonRequest<JSONObject> {
String stringRequest;
/**
* 这里的method必须是Method.POST,也就是必须带参数。
* 如果不想带参数,可以用JsonObjectRequest,给它构造参数传null。GET方式请求。
* @param stringRequest 格式应该是 "key1=value1&key2=value2"
*/
public MyJsonObjectRequest(String url, String stringRequest,
Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Method.POST, url,stringRequest , listener, errorListener);
this.stringRequest = stringRequest;
}
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
}
@Override
protected Response<JSONObject> 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));
}
}
}
调用方法:
MyJsonObjectRequest jsonObjectRequest=new MyJsonObjectRequest(url, "username="+str+"&userpwd=123",new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Gson gson=new Gson();
String name=response.getString("username");
int age=Integer.parseInt(response.getString("userage"));
String sex=response.getString("usersex");
Toast.makeText(MainActivity.this, name+","+age+","+sex, Toast.LENGTH_SHORT).show();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
}
});
第三步,将Request加入到RequestQueue中 queue.add(stringRequest);
注意Request请求可以在任意线程中添加,但是回调是在主线程中的
1)StringRequest
requestQueue.add(stringRequest);
2)JsonObjectRequest
requestQueue.add(jsonObjectRequest);
整个代码:
1、导入volley包
2、在AndroidManifest.xml中配置网络权限<uses-permission android:name="android.permission.INTERNET"/>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.volleyuse"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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" >
<activity
android:name="com.example.volleyuse.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>
activity_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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="使用volley框架中的StringRequest" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="使用volley框架中的JsonObjectRequest" />
</LinearLayout>
package com.example.util;
import java.io.UnsupportedEncodingException;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
public class MyJsonObjectRequest extends JsonRequest<JSONObject> {
String stringRequest;
/**
* 这里的method必须是Method.POST,也就是必须带参数。
* 如果不想带参数,可以用JsonObjectRequest,给它构造参数传null。GET方式请求。
* @param stringRequest 格式应该是 "key1=value1&key2=value2"
*/
public MyJsonObjectRequest(String url, String stringRequest,
Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Method.POST, url,stringRequest , listener, errorListener);
this.stringRequest = stringRequest;
}
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
}
@Override
protected Response<JSONObject> 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));
}
}
}
package com.example.volleyuse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.util.MyJsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button btn1,btn2;
private RequestQueue requestQueue;
//请求的服务器地址
private static final String url="http://192.168.1.106:8080/VolleyServer/UserServlet";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button) findViewById(R.id.btn1);
// 第一步,实例化请求对象RequestQueue,队列只能有一个
requestQueue=Volley.newRequestQueue(MainActivity.this);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 第二步,新建一个Request,
// @参数method 网络请求方式(Get, Post等,一般采用post方式)
// @参数url 网络请求地址
// @参数listener 成功后的处理
// @参数errorListener 失败后的处理
// 如果需要传递传递参数,需要重写getParams方法。
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String, String> getParams()
throws AuthFailureError {
Map<String,String> map=new HashMap<String, String>();
map.put("username", "小明");
map.put("userpwd", "123");
return map;
}
};
// 第三步,将Request加入到RequestQueue中 requestQueue.add(stringRequest);
// 注意Request请求可以在任意线程中添加,但是回调是在主线程中的
requestQueue.add(stringRequest);
}
});
btn2=(Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
requestQueue=Volley.newRequestQueue(MainActivity.this);
String str="小明";
try {
str=URLEncoder.encode(str, "utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
MyJsonObjectRequest jsonObjectRequest=new MyJsonObjectRequest(url, "username="+str+"&userpwd=123",new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Gson gson=new Gson();
String name=response.getString("username");
int age=Integer.parseInt(response.getString("userage"));
String sex=response.getString("usersex");
Toast.makeText(MainActivity.this, name+","+age+","+sex, Toast.LENGTH_SHORT).show();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
}
});
/*JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url+"?username="+str+"&userpwd=123", null,new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String name=response.getString("username");
int age=Integer.parseInt(response.getString("userage"));
String sex=response.getString("usersex");
Toast.makeText(MainActivity.this, name+","+age+","+sex, Toast.LENGTH_SHORT).show();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
}
});*/
// 第三步,将Request加入到RequestQueue中requestQueue.add(jsonObjectRequest);
// 注意Request请求可以在任意线程中添加,但是回调是在主线程中的
requestQueue.add(jsonObjectRequest);
}
}
);
}
}
3、MyEclipse
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
public class UserServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public UserServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//防止写回的数据乱码
response.setContentType("application/json;charset=utf-8");
String name=request.getParameter("username");
name=new String(name.getBytes("iso-8859-1"), "utf-8");
String pwd=request.getParameter("userpwd");
PrintWriter out = response.getWriter();
if ("小明".equals(name)&&"123".equals(pwd)) {
Map<String,String> map=new HashMap<String, String>();
map.put("username", name);
map.put("userage", "23");
map.put("usersex", "男");
Gson gson=new Gson();
String mapString=gson.toJson(map);
out.print(mapString);
System.out.println("get验证通过"+mapString);
}else {
out.print("get验证失败");
System.out.println("get验证失败");
}
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//防止写回的数据乱码
response.setContentType("application/json;charset=utf-8");
String name=request.getParameter("username");
String pwd=request.getParameter("userpwd");
PrintWriter out = response.getWriter();
if ("小明".equals(name)&&"123".equals(pwd)) {
Map<String,String> map=new HashMap<String, String>();
map.put("username", name);
map.put("userage", "23");
map.put("usersex", "男");
Gson gson=new Gson();
String mapString=gson.toJson(map);
out.print(mapString);
System.out.println("post验证通过"+mapString);
}else {
out.print("post验证失败");
System.out.println("post验证失败");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}