你不能使用asynctask . Volley关心它 . 您可以使用回调来处理数据和ui . 看起来像这样:
public class LoginActivity extends SinglePaneActivity implements DownloadCallback {
//...
public void sendRequest(){
Downloader download = new Download(this);
downloader.download(userName, password);
progresbar.show();
}
public void requestFinish(){
progersbar.dismis();
//... continue
}
}
打回来:
public interface DownloadCallback {
void requestFinish();
}
在课程下载器中
private RequestQueue requestQueue;
DownloadCallback mcallback;
public void Downloader(DownloadCallback callback){
mCallback = callback;
requestQueue = Volley.newRequestQueue(mContext);
initVolleyListeners();
}
private void initVolleyListeners() {
mSuccessListener = new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
mCallback.requestFinish();
}
};
mErrorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mCallback.requestFinish();
}
};
public void download(String user, String pass){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, createJson(user, pass), mSuccessListener , mErrorListener ) {
//header for send JSON to server
@Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
requestQueue.add(jsonObjectRequest );
}
还有一点 . 不要在json中发送用户名 . 你把它作为param发送到 Headers 中 . 使用此 application/x-www-form-urlencoded 并设置将用户名传递为 Headers 中的params .