okhttp usage

  1. Get operations (get operating parameter is spliced ​​back the url)
     1 public void doGet(View view) {
     2         //1.拿到okHttpClient对象
     3   //      OkHttpClient okHttpClient = new OkHttpClient();
     4         //2、构造Request
     5         Request.Builder builder = new Request.Builder();
     6         Request request = builder
     7                 .get()
     8                 .url(mBaseUrl+"login?username=cyd&password=1234")
     9                 .build();
    10         //3、4
    11         executeRequest(request);
    12     }

     

  2. GAT, POST extracted Public Methods
    . 1  public  void the executeRequest (Request Request) {
     2          // . 3, packaged as a Request Call 
    . 3          Call Call = okHttpClient.newCall (Request);
     . 4          // . 4, performs Call (callback return value response, not within the UI thread ) 
    . 5          call.enqueue ( new new the Callback () {
     . 6              @Override
     . 7              public  void the onFailure (the Request Request, IOException E) {
     . 8                  Le ( "the onFailure" + e.getMessage ());
     . 9              }
     10              @Override
     . 11              public  void onResponse ( Response response)throws IOException {
     12 is                  Le ( "onResponse:" );
     13 is                  Final String STR = response.body () String ();.
     14                  //              textView.setText (STR); UI inoperable child thread
     15                  @ right way: 
    16                  runOnUiThread ( new new the Runnable () {
     . 17                      @Override
     18 is                      public  void RUN () {
     . 19                          textView.setText (STR);
     20 is                      }
     21 is                  });
     22 is              }
     23 is          });
    24 
    25     }

     

  3. Post (post a request body parameters are configured the responseBody)
    . 1  public  void the doPost (View View) {
     2          // 1. okHttpClient objects to get
     3          // 2, the configuration of the Request
     . 4          // 2.1 configured requestBody
     . 5          // FormEncodingBuilder parameter is passed the post Builder 
    . 6          FormEncodingBuilder requestBodyBuilder = new new FormEncodingBuilder ( );
     . 7          requestBody requestBody = requestBodyBuilder
     . 8                  .add ( "username", "CyD" )
     . 9                  .add ( "password", "123456789" ) .build ();
     10  
    . 11          Request.Builder Builder = new new Request.Builder();
    12         Request request = builder.url(mBaseUrl + "login").post(requestBody).build();
    13         //3、4
    14         executeRequest(request);
    15     }

     

     

  4. POST a JSON string
    . 1  public  void doPostString (View View) {
     2          // String to send it out as requestBody, the above method is only different construction of requestBody
     3          // only need to use a string post configured by the mode FormEncodingBuilder
     . 4  
    . 5          // first parameters comprising type and character encoding, the second string 
    . 6          requestBody requestBody = RequestBody.create (MediaType.parse ( "text / Plain; = UTF-chaset. 8"), "{username: CyD, password: 09876}" ) ;
     . 7          Request.Builder Builder = new new Request.Builder ();
     . 8          the Request = Request builder.url (mBaseUrl + "postString" ) .post (requestBody) .build ();
     . 9          // 3,4- 
    10         executeRequest(request);
    11     }

     

    Server print out the string result:

     

  5. Server code:
     1 public String login() {
     2         System.out.println(username+","+password);
     3         HttpServletResponse response = ServletActionContext.getResponse();
     4         try {
     5             PrintWriter writer = response.getWriter();
     6             writer.write("login success!");
     7             writer.flush();
     8         } catch (IOException e) {
     9             // TODO Auto-generated catch block
    10             e.printStackTrace();
    11         }        
    12         return null;        
    13     }
    14     public String postString() {
    15         HttpServletRequest request = ServletActionContext.getRequest();
    16         try {
    17             ServletInputStream iServletInputStream = request.getInputStream();
    18             
    19             StringBuilder sb = new StringBuilder();
    20             int len =0;
    21             byte[] buf = new byte[1024];
    22             while((len = iServletInputStream.read(buf))!= -1) {
    23                 sb.append(new String (buf,0 ,len));
    24             }
    25             System.out.println(sb.toString());
    26             
    27         } catch (IOException e) {
    28             // TODO Auto-generated catch block
    29             e.printStackTrace();
    30         }
    31         
    32         return null;
    33     }

     

  6. The server receives the parameters are obtained by a member variable, the client receives the data server is usually through a callback to get inside the response inputStream, service clients to obtain data flows through the client's request is to get
  7. session to keep the problem: the server after the user logs will produce a sessionID, sessionID will return in the form of a cookie to the client, if the client get the sessionID server sessionID still can not login repeat the life cycle, the user can determine as whether logged in. You can get sessionID
  8. Notes from: https://www.imooc.com/learn/764

Guess you like

Origin www.cnblogs.com/cydqqq/p/11203420.html