简体   繁体   中英

AsyncTask in Android

I have a client Class that connects to the server and sends a POST request and in response gets a Json answer.

public class ClientLocal extends AsyncTask<Void, Void, String> {

private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");  //Media type for request


public JSONObject all_info_json;

private String page;

private SharedPreferences prefs;

private String login;
private String pass;
private StringBuilder request_body = new StringBuilder();
private OkHttpClient client = new OkHttpClient();

protected String doInBackground(Void... params) {
    RequestBody body = RequestBody.create(JSON, request_body.toString());
    Request request = new Request.Builder()
            .url("https://program.yousystem.com.ua/frontend/api/user/login")
            .post(body)
            .build();
    try (Response response = client.newCall(request).execute()) {
        page = response.body().string();
        //Log.i("PAGE", "page from try" + page);
        return page;

    } catch (IOException e) {
        Log.i("ERROR", "1" + e.toString());
        e.printStackTrace();
        return null;
    }

}


protected void onPostExecute(String page) {

    try {
        all_info_json = (JSONObject) new JSONTokener(page).nextValue();

        JSONObject response = all_info_json.getJSONObject("response");
        Log.i("PAGE", "RESP" + response.toString());

        String token = response.getString("token");
        Log.i("PAGE", "TOKEN " + token);

        JSONObject profile = response.getJSONObject("profile");
        Log.i("PAGE", "PROFILE" + profile.toString());

        JSONArray balances = profile.getJSONArray("balances");
        JSONObject balance_obj = balances.getJSONObject(0);
        String balance = balance_obj.getString("balance");
        Log.i("PAGE", "Balance" + balance);

        JSONObject person = profile.getJSONObject("person");
        String firstName = person.getString("firstName");
        String lastName = person.getString("lastName");
        String mobile = person.getString("mobile");
        String email = person.getString("email");

    } catch (JSONException e) {
        e.printStackTrace();
    }

    //  Log.i("PAGE", "page from post" + page);

}

ClientLocal(String login, String pass) {
    this.login = login;
    this.pass = pass;
    this.request_body.append("{username: \"");
    this.request_body.append(login);
    this.request_body.append("\", pass: \"");
    this.request_body.append(pass);
    this.request_body.append("\", lng: \"ua\", prgCode: \"prg1\"}\"");
    Log.i("", "page constructor" + request_body.toString());

}}

I need to execute all requests in one Client Class using AsyncTask, can anyone help me, how to do this? Because to run a request I use ClientLocal client = new ClientLocal("login","pass"); and after that client.execute(); In my opinion I need to create Request builder class. But how to use it in Client local?

public class RequestBuilder {

final private static String login_string = "https://program.yousystem.com.ua/frontend/api/user/login";
final private static String about_me = "https://program.yousystem.com.ua/frontend/api/user/me";
final private static String about_me_edit = "https://program.yousystem.com.ua/frontend/api/user/save";
final private static String transaction_list = "https://program.yousystem.com.ua/frontend/api/transaction/list";

String card_number;
String password;

StringBuilder request_body_login = new StringBuilder();

public RequestBuilder(String card_number_, String password_) {
    this.card_number = card_number_;
    this.password = password_;
}

public String LoginRequest(){

    this.request_body_login.append("{username: \"");
    this.request_body_login.append(card_number);
    this.request_body_login.append("\", pass: \"");
    this.request_body_login.append(password);
    this.request_body_login.append("\", lng: \"ua\", prgCode: \"prg1\"}\"");
    Log.i("", "page constructor" + request_body_login.toString());
    return request_body_login.toString();
}}

Login request

    Post https://program.yousystem.com.ua/frontend/api/user/login
Request {
  "username": "username",
  "pass": "pass",
  "lng": "ua",
  "prgCode": "prg1"
}

Get profile info

    Post https://program.yousystem.com.ua/frontend/api/user/me
Request {
  "prgCode": "prg1",
  "token": "XT4PHNZBMSK73C7KH33NDJCN8A4SP5CJ"
}

Transaction list

Post https://program.yousystem.com.ua/frontend/api/transaction/list
Request {
  "withLimit": true,
  "prgCode": "prg1",
  "token": "XT4PHNZBMSK73C7KH33NDJCN8A4SP5CJ"
}

You can have a class with the methods for each request

public class MyRequests{
   private jsonParser;
   public MyRequests(){
     jsonParser = new JSONParser()  

   }
   //request login
   public JSONObject loginRequest(String username,String password, String prgCode, String language){
     // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("password", password));
    params.add(new BasicNameValuePair("prgCode", prgCode));
    params.add(new BasicNameValuePair("lang", language));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);

    return json;
   }

    //request profile info
   public JSONObject profileRequest(String prgCode,String token){
     // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("prgCode", prgCode));
    params.add(new BasicNameValuePair("token", token));
    JSONObject json = jsonParser.getJSONFromUrl(profileURL, params);

    return json;
   }
}

Then you can call each one in their respective activity in asyncTask

protected String doInBackground(String... args){
   MyRequests request = new MyRequest();
   jsonObject = request.loginRequest(username,password);

   //handle json object here




return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM