Three modes of Android GET and POST network request

  • 2021-10-27 08:47:22
  • OfStack

Our applications often need to get the data on the network through networking, and then analyze it. We must get the data first before we can carry out the next step of business.

Therefore, network request is a common operation. Let me introduce three common ways.

The first is a more primitive method, using HttpURLConnection, The second is the Volley framework. The third is the xutils3 framework.

1. HttpURLConnection method

This is a network request based on HTTP protocol for network communication, and the other two frameworks are also based on HTTP protocol. HTTP protocol is a protocol based on short connection, and the connection is disconnected after each interaction, while HTTP request is divided into GET and POST. GET request is relatively simple and only needs to be used behind the website? Splice the resource path of the request, such as the address of Baidu picture input animation keyword

http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8A%A8%E6%BC%AB , 

Can you see index? Followed by a lot & Connected project, this & What does the last word=% E5% 8A% A8% E6% BC% AB mean

Is the input of two words "animation", which is UTF-8 encoded bytes, Chinese 1 character will be compiled into 3 bytes, which is represented by 1 byte in hexadecimal.

We can also see one limitation of GET request, that is, it can't pass Chinese, and it is not suitable for data submission with large amount of data.

While POST does not have this limitation, and its security is higher than GET request. In summary, GET is used for simple network requests, and POST is used for complex interactions with servers.

The next step is to send an GET request and an POST request.

GET Request


  //1. URL
    URL url = new URL("http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8A%A8%E6%BC%AB");
    //2. HttpURLConnection
    HttpURLConnection conn=(HttpURLConnection)url.openConnection();
    //3. set(GET)
    conn.setRequestMethod("GET");
    //4. getInputStream
    InputStream is = conn.getInputStream();
    //5.  Analyse is , get the responseText Where buffered character streams are used 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while((line=reader.readLine()) != null){
      sb.append(line);
    }
    // Get the response text 
    String responseText = sb.toString();

POST Request


//1. URL
    URL url = new URL("http://image.baidu.com/search/index");
    //2. HttpURLConnection
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    //3. POST
    conn.setRequestMethod("POST");
    //4. Content-Type, Here is the fixed writing, the type of content sent 
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //5. output Here, remember to open the output stream, write the parameters you want to add with this output stream and pass them to the server. This is socket The basic structure of 
    conn.setDoOutput(true);
    OutputStream os = conn.getOutputStream();
    String param = "tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8A%A8%E6%BC%AB";
    //1 Remember to convert your parameters to bytes, and the encoding format is utf-8
    os.write(param.getBytes("utf-8"));
    os.flush();
    //6. is
    InputStream is = conn.getInputStream();
    //7.  Analyse is , get the responseText
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while((line=reader.readLine()) != null){
      sb.append(line);
    }
    // Get the response text 
    String responseText = sb.toString();

2. Volley Framework

GET Request


  //1.  Create RequestQueue, This is 1 Request queues, equivalent to message mechanism processing 
  private RequestQueue  mQueue = Volley.newRequestQueue(this);
    //2. StringRequest
    String url = "http://www.baidu.com";
    StringRequest req = new StringRequest(url, 
        new Listener<String>() {
          // Callback after successful request   Execute in the main thread 
          public void onResponse(String responseText) {
            // Analyse json  Encapsulate the result data 
            Gson gson = new Gson();
            // Used here Gson Analyse JSON String       
            User result=gson.fromJson(responseText,RequestResult.class);
                      }
        }, new ErrorListener() {
          // When a request goes wrong   Execute a callback   Execute in the main thread 
          public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
          }
        });
  // Put req  Add to   In the request queue, 1 Be sure to remember this 1 Step, otherwise it is equivalent to not sending the request 
    mQueue.add(req);

POST Request


private RequestQueue mQueue; 
//post Request to use commonRequest Request implementation 
  String url="www.baidu.com";
  CommonRequest request = new CommonRequest(Request.Method.POST,url,new Response.Listener<String>() {
      public void onResponse(String response) {
        try {
        // Here is the interface called after the request is successful, using JSON Tools parse data 
          JSONObject obj = new JSONObject(response);
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
    },new Response.ErrorListener() {
      public void onErrorResponse(VolleyError error) {
      }
    }){
      // If you use POST Request, to add parameters, 1 You must override this method to add parameters 
      @Override
      protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> resultMap = new HashMap<String, String>();
        // The specific parameters added here    resultMap.put("username",user.getName());
        resultMap.put("userAge",user.getAge());
        resultMap.put("userGender",user.getGender());
resultMap.put("userSchool",user.getSchool());
        return resultMap;
      }
    };
    mQueue.add(request);
  }

3. Xutils3 Framework

GET Request


// No. 1 1 Step, new 1 Request parameter objects 
RequestParams params=new RequestParams("www.baidu.com?inm=2");
// Direct call x.http().get() Method, note here that x Is to use the global MyApplication Can only be used after initialization in, and the initialization method is x.Ext.init(this)
    x.http().get(params, new Callback.CommonCallback<String>() {
      @Override
      public void onCancelled(CancelledException arg0) {
      }
      @Override
      public void onError(Throwable arg0, boolean arg1) {
        Log.i("hap.zhu", "http_on_error, Failed to request network data ");
      }
      @Override
      public void onFinished() {
      }
      @Override
      public void onSuccess(String result) {
        Log.i("hap.zhu", " The result of the request data is :"+result);
        Gson gson=new Gson();
        Result result=gson.fromJson(result,Result.class);
        Log.i("hap.zhu", " The loading result is :"+result.toString());
    }
    });

POST Request


// The method is the same as GET It's as simple as that. If the network request succeeds, it will be called back to the listener success Interface, just process the data results directly 
  RequestParams params=new RequestParams("www.baidu.com");
    params.addBodyParameter("email", username);
    params.addBodyParameter("password", password);
    x.http().post(params, new CommonCallback<String>() {
      @Override
      public void onCancelled(CancelledException arg0) {
      }
      @Override
      public void onError(Throwable arg0, boolean arg1) {
        // Network errors also prompt errors 
        callback.Error(arg0.toString());
      }
      @Override
      public void onFinished() {
      }
      @Override
      public void onSuccess(String result) {
        Gson gson=new Gson();
      LoginResult loginResult=gson.fromJson(result, LoginResult.class);

Summarize


Related articles: