简体   繁体   中英

Android: Changing HTTP library from Volley to OkHttp

I'm changing the HTTP library from Volley to OkHttp in my application, as Volley is not valid in API level 23 (because Volley APIs consist of the deprecated libraries). The original code that I'm now trying to modify is about registering a new user as follows, and is currently using Volley APIs.

private void registerUser(final User newUser) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        pDialog.setMessage("Registering");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register response: " + response);
                hideDialog();
                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if(!error) {
                        // User successfully stored in MySQL
                        // Now store the user in sqlite
                        String userUid = jObj.getString("uid");
                        JSONObject user = jObj.getJSONObject("user");
                        String userEmail = user.getString("email");
                        String userName = user.getString("name");
                        String userGender = user.getString("gender");
                        String userBirthday = user.getString("birthday");
                        String userCreated_at = user.getString("created_at");

                        // Inserting row in users table
                        db.addUser(userEmail, userName, userGender, userBirthday, userUid, userCreated_at);

                        // Launch mainscreen activity
                        Intent intent = new Intent(RegisterActivity.this, MainScreenActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error occurred in registration. Get the error message.
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch(JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("tag", "register");
                params.put("email", newUser.getEmail());
                params.put("name", newUser.getName());
                params.put("gender", newUser.getGender());
                params.put("password", newUser.getPassword());
                params.put("birthday", newUser.getBirthday());
                return params;
            }
        };
        // Adding request to to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

And here's the addToRequestQueue which belongs to the AppController class, which is denoted in the tag in the Androidmanifest.xml file.

public <T> void addToRequestQueue(StringRequest req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

I'm just new to OkHttp, and I've already spend quite a long time how to solve out this problem. Any good tips will be appreciated.

OkHttp works almost in the same way so you can change the library easily. You should first create the Http client:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
      @Override
        public void onFailure(Request request, IOException e) {
            // if something goes wrong
        }

        @Override
        public void onResponse(Response response) throws IOException {
           // Here you get the response and parse it
           String response = response.body().string();
        }
}

Hope it will help you.

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