简体   繁体   English

Android:将HTTP库从Volley更改为OkHttp

[英]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). 我正在将我的应用程序中的HTTP库从Volley更改为OkHttp,因为Volley在API级别23中无效(因为Volley API包含已弃用的库)。 The original code that I'm now trying to modify is about registering a new user as follows, and is currently using Volley APIs. 我现在尝试修改的原始代码是关于如下注册新用户的,并且当前正在使用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);
    }

And here's the addToRequestQueue which belongs to the AppController class, which is denoted in the tag in the Androidmanifest.xml file. 这是属于AppController类的addToRequestQueue,在Androidmanifest.xml文件的标记中表示。

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. 我只是OkHttp的新手,并且我已经花了很长时间来解决这个问题。 Any good tips will be appreciated. 任何好的提示将不胜感激。

OkHttp works almost in the same way so you can change the library easily. OkHttp的工作方式几乎相同,因此您可以轻松更改库。 You should first create the Http client: 您应该首先创建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();
        }
}

Hope it will help you. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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