在 AsyncTask 中调用 okhttp3.Callback 中的方法发现不是线程阻塞的,关键代码如下:
public class HttpUtil {
//以上代码省略
public static void sendPostHttpRequestOkHttp(String address, PostFormBuilder builder, okhttp3.Callback callback) {
OkHttpClient client = new OkHttpClient();
RequestBody body = builder.onBuild();
Request request = new Request.Builder().url(address).post(body).build();
client.newCall(request).enqueue(callback);
}
public interface PostFormBuilder {
RequestBody onBuild();
}
}
MainActivity 中调用的相关代码:
public class LoginActivity extends AppCompatActivity {
//以上代码省略
private class LoginTask extends AsyncTask<Void, Void, Boolean> {
String mPassword;
String mUsername;
boolean success = false;
LoginTask(String mPassword, String mUsername) {
this.mPassword = mPassword;
this.mUsername = mUsername;
}
@Override
protected Boolean doInBackground(Void... params) {
HttpUtil.sendPostHttpRequestOkHttp(LOGIN_URL, new HttpUtil.PostFormBuilder() {
@Override
public RequestBody onBuild() {
return new FormBody.Builder().add("username", mUsername).add("password", mPassword).build();
}
}, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
String respData = response.body().string();
Log.d("Main", respData);
try {
JSONObject object = new JSONObject(respData);
int res = object.getInt("result");
success = (res == 100);
Log.d("Main","resp "+success);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Log.d("Main","return "+success);
return success;
}
@Override
protected void onPreExecute() {
loginProgress.setVisibility(ProgressBar.VISIBLE);
}
@Override
protected void onPostExecute(Boolean suc) {
loginProgress.setVisibility(ProgressBar.GONE);
if (suc) {
showDialog();
} else {
inputPassword.setError("密码错误");
inputPassword.requestFocus();
}
}
@Override
protected void onCancelled() {
Toast.makeText(LoginActivity.this, "Login Canceled", Toast.LENGTH_SHORT).show();
}
}
}
实际执行的时候总是先return false 然后才修改success的值为true,发现callback是异步执行的,自己实现一个callback如下之后运行达到期望目标
public class HttpUtil {
public static void sendPostHttpRequestOkHttp(String address, PostFormBuilder builder, RequestCallback callback){
OkHttpClient client = new OkHttpClient();
RequestBody body = builder.onBuild();
Request request = new Request.Builder().url(address).post(body).build();
Response resp = null;
try {
resp = client.newCall(request).execute();
} catch (IOException e) {
callback.exceptionHandler(e);
}
callback.responseHandler(resp);
}
public interface PostFormBuilder {
RequestBody onBuild();
}
public interface RequestCallback {
void responseHandler(Response response);
void exceptionHandler(Exception e);
}
}