我有字符串数组:
public static final String[] LACCOUNT =
{
"username=admin1&password=saa123456",
"username=admin2&password=klk123456",
"username=admin3&password=exf123456",
"username=admin4&password=uoq123456",
"username=admin5&password=qff123456"
};
我有
public void okGet(String URL, String param) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL + "?" + param)
.get()
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String textResponse = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (textResponse.contains(":1")) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "YES", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
我想用AsyncTask
我已经尝试过这样,但它无法正常工作
private class aTaskWorker extends AsyncTask<String, Void, String> {
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
fab1.setVisibility(View.GONE);
tvLog.setText(s);
// tvLog.setText(response.body().string());
// Kondisi
String strResult = tvLog.getText().toString();
if (strResult.contains(":1")) {
// TODO : stop this loop
}
}
@Override
protected String doInBackground(String... params) {
int totAkun = Constans.LACCOUNT.length;
for (int i = 0; i < totAkun; i++) {
int counter = i + 1;
tvTask.setText(counter + " of " + totAkun);
OKPost(Constans._LOGIN, Constans.LACCOUNT[i]);
}
return null;
}
AsyncTask
怎么做?
TQ
答案 0 :(得分:0)
首先,您需要修复 okGet()功能才能使用同步请求。由于您已经使用AsyncTask(异步操作)来循环请求,因此请求必须是同步的。
public String tryLogin(String URL, String param) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL + "?" + param)
.get()
.build();
try {
Response response = client.newCall(request).execute();
if (response != null && response.body() != null) {
return response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
然后,您修改AsyncTask来执行此操作:
private static class LoginAsyncTask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... accounts) {
for (String account : accounts) {
// try to login each account from array of accounts
String loginResult = tryLogin(Constants.LOGIN, account);
if (loginResult != null && loginResult.contains(":1")) {
return true;
}
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// hide progress bar
if (result) {
// Successful login
} else {
// Failed login
}
}
}
然后使用以下函数调用AsyncTask:
new LoginAsyncTask().execute(Constants.LACCOUNT);