Android:将Volley从Volley更改为OkHttp

时间:2015-09-28 20:05:25

标签: android okhttp

我在我的应用程序中将HTTP库从Volley更改为OkHttp,因为Volley在API级别23中无效(因为Volley API包含已弃用的库)。我现在尝试修改的原始代码是关于注册新用户,如下所示,目前正在使用Volley API。

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);
    }

这是属于AppController类的addToRequestQueue,它在Androidmanifest.xml文件的标记中表示。

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

我刚认识OkHttp,我已经花了很长时间才解决这个问题。任何好的提示将不胜感激。

1 个答案:

答案 0 :(得分:0)

OkHttp的工作方式几乎相同,因此您可以轻松更改库。 您应该首先创建Http客户端:

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();
        }
}

希望它会对你有所帮助。