doGet方法
private void doGet() {
StringRequest stringRequest=new StringRequest(Request.Method.GET, "http://192.168.0.30:8080/MyWebTest/MyTestServerlet", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mTextViewContent.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextViewContent.setText("网络连接错误");
}
});
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
doPost方法
private void doPost() {
StringRequest stringRequest=new StringRequest(Request.Method.POST, "http://192.168.0.30:8080/MyWebTest/MyTestServerlet", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mTextViewContent.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextViewContent.setText("网络连接错误");
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> map=new HashMap<>();
map.put("username","liuyu");
return map;
}
};
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
MySingleton
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}