Use the okhttp framework to implement user login including verification code and maintain session operation (Part 1)

Use the okhttp framework to implement user login including verification code and maintain session operation (Part 1)

1. What problem does this article solve and what can we learn?

I am working on a hospital affairs system project recently, so I will record the process of learning new knowledge. This article is about the login operation. I originally thought that the login process was a relatively simple thing, but after a deeper understanding, it is still difficult:

1. To obtain the verification code photo during the login process, use the HTTP get operation. To pass the parameters to the server, you need to use post.

2. The above get and post operations can be implemented using many current network frameworks, such as volley, but after obtaining the verification code photo, a session must be maintained. Therefore, after consulting the information, it is more convenient and quick to use the okhttp framework to build this project.

Let's first learn how to use okhttp: http://blog.csdn.net/itachi85/article/details/51190687

There is also a quick start to load photos using okhttp:

http://blog.csdn.net/bo543937071/article/details/53380651

2. Q: What are sessions and cookies?

Simply put, cookie is the session ID of the client, and session is the session ID of the server. Based on this ID number, you can query the content of your session.

(To learn more about cookies and sessions, click here)

http://blog.csdn.net/androidxiaogang/article/details/51925388

In this project, we need to obtain the verification code photo. Because each time you refresh the verification code URL, a different verification code photo will appear, so you need to save the verification code session, otherwise how can others know which verification code you have a "session" with. First, the photo:

As shown in the figure, it is divided into four steps, which is easier to understand with text:

1. The client sends a request for a verification code photo, and brings back the photo and a jsessionid field that is stored in the user's cookie.

2. We take out the session from the cookie header, and then pack the parameters and send it along with the session so that the server knows who sent it.

The four steps and two points of summary make it easier to understand with the code.

3. Analyze some important codes and then paste all the codes

Let's take a look at the data given to us by the backend. There is url_randCodeImage used to send a get request to obtain photos, and url_login used to post data. These are the data we want to package and send:

And our xml interface

First, we get our verification code photo and load the picture asynchronously

  1. //Send a request to get the verification code photo
  2. private void ChangeImage() {
  3. Request request = new Request.Builder()
  4. .url(App.url_randCodeImage)
  5. .build();
  6. Call call = okHttpClient.newCall(request);
  7. call.enqueue(new Callback() {
  8. @Override
  9. public void onFailure(Call call, IOException e) {
  10. Log.i( "info_callFailure" ,e.toString());
  11. }
  12.   
  13. @Override
  14. public void onResponse(Call call, Response response) throws IOException {
  15. byte[] byte_image = response.body().bytes();
  16.   
  17.   
  18. //Update the UI through the handler
  19. Message message = handler.obtainMessage();
  20. message.obj = byte_image;
  21. message.what = SUCCESS;
  22. Log.i( "info_handler" , "handler" );
  23. handler.sendMessage(message);
  24.   
  25. //Operation of getting session, session is placed in the cookie header, and after being taken out, it contains ";", after being taken out, it is the following s (that is, jsesseionid)
  26. Headers headers = response.headers();
  27. Log.d( "info_headers" , "header " + headers);
  28. List<String> cookies = headers. values ​​( "Set-Cookie" );
  29. String session = cookies.get(0);
  30. Log.d( "info_cookies" , "onResponse-size: " + cookies);
  31.   
  32. s = session.substring (0, session.indexOf( ";" ));
  33. Log.i( "info_s" , "session is :" + s);
  34.   
  35. }
  36. });
  37. }
  38.   
  39. // Load the image asynchronously
  40. public Handler handler = new Handler(){
  41. @Override
  42. public void handleMessage(Message msg) {
  43. switch (msg.what){
  44. // Load the network successfully to update the UI and process the obtained image resources
  45. case SUCCESS:
  46. //Get the byte array through message
  47. byte[] Picture = (byte[]) msg.obj;
  48. //Use the BitmapFactory factory to convert the byte array into a bitmap
  49. Bitmap bitmap = BitmapFactory.decodeByteArray(Picture, 0, Picture.length);
  50. //Set the picture through imageview
  51. img_identy.setImageBitmap(bitmap);
  52.   
  53. break;
  54. //Logic code executed when loading network fails
  55. case FALL:
  56. Toast.makeText(MainActivity.this, "There is a problem with the network" , Toast.LENGTH_SHORT).show();
  57. break;
  58. }
  59. }
  60. };

After getting the photos and session, we package and send the data:

  1. private void LoginServer() {
  2. Log.i( "info_Login" , "Known session:" +s);
  3. OkHttpClient client = new OkHttpClient();
  4. FormBody body = new FormBody.Builder()
  5. . add ( "userName" ,et_username.getText().toString())
  6. . add ( "password" ,et_code.getText().toString())
  7. . add ( "randCode" ,et_identy.getText().toString())
  8. . add ( "langCode" , "zh-cn" )
  9. .build();
  10. Request request = new Request.Builder()
  11. .addHeader( "cookie" ,s)
  12. .url(App.url_login)
  13. .post(body)
  14. .build();
  15. Call call2 = okHttpClient.newCall(request);
  16. call2.enqueue(new Callback() {
  17. @Override
  18. public void onFailure(Call call, IOException e) {
  19. Log.i( "info_call2fail" ,e.toString());
  20. }
  21.   
  22. @Override
  23. public void onResponse(Call call, Response response) throws IOException {
  24. if(response.isSuccessful()){
  25. Log.i( "info_call2success" ,response.body().string());
  26. }
  27. Headers headers = response.headers();
  28. Log.i( "info_respons.headers" ,headers+ "" );
  29.   
  30. }
  31. });
  32. }

***Let's take a look at the information logged out after we successfully logged in

*** Here is our full code, I hope it will be helpful to those who don’t understand the process:

Continue

<<:  Building iOS Routers Step by Step

>>:  iOS Developer Account Summary

Recommend

4 tips for user growth!

To achieve sustained growth, people must be the f...

How to create high-conversion information flow video content!

With regard to information flow advertising, ther...

From 1 to 10, how to build a product user system!

As the product ecosystem improves, user growth wi...

APP promotion: How to increase users three times at low cost?

1. Project Background A domestic financial APP pr...

Uncovering the Violent Pornography on WeChat

“You can never cheat the Chinese out of their mon...

Why Apple's licensing of its iOS operating system was a bad move

In response to the declining sales of Apple iPhon...

8 tips to teach you how to make good use of KOL!

Although routines are necessary, you must also be...

How much does it cost to produce a Zhengzhou beauty mini program?

How much is the quote for beauty makeup productio...

Just 2 steps to permanently turn off Win10 automatic updates

It's not that Windows 10 is bad, but Microsoft...

The copy targeting is the same, why is the CTR still lower than others?

The copywriting is obviously very well written, s...