package com.youjiaopingtai.api.http;
import android.content.Context;
import android.util.Log;
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.youjiaopingtai.api.util.LogUtils;
import org.json.JSONObject;
/**
* Created by Administrator on 2018/8/16.
*/
public class VolleyHttp {
private static String TAG = "VolleyHttp";
public static RequestQueue mQueue = null;
public static void getInstance(Context context) {
if (mQueue == null) {
synchronized (context) {
mQueue = Volley.newRequestQueue(context);
}
}
}
/**
* Get 请求
*
* @param url 接口地址
* @param what 回调地址
*/
public static void get(final HttpCallBack httpCallBack, final int what, String url) {
LogUtils.e(TAG, url);
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e(TAG, "onResponse: " + response);
httpCallBack.onResponse(what, response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: " + error.toString());
httpCallBack.onErrorResponse(error.toString());
}
});
mQueue.add(request);
}
/**
* Post 请求
*
* @param strurl 请求路径
* @param jsonObject 携带参数
* @param what 回调位置
*/
public static void post(final HttpCallBack httpCallBack, String strurl, JSONObject jsonObject, final int what) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, strurl, jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
Log.e(TAG, "onResponse: " + jsonObject.toString());
httpCallBack.onResponse(what, jsonObject.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.e(TAG, "onErrorResponse: " + volleyError.toString());
httpCallBack.onErrorResponse(volleyError.toString());
}
});
mQueue.add(jsonObjectRequest);
}
public interface HttpCallBack {
/**
* 调用接口响应成功信息
*/
void onResponse(int what, String response);
/**
* 调用接口出错信息
*/
void onErrorResponse(String error);
}
}