SoFunction
Updated on 2025-04-09

Three ways to request Android GET and POST network

Our applications often need to connect to the Internet to obtain data on the network and then parse it. They must first obtain the data before they can proceed to the next business.

Therefore, network request is a common operation. I will introduce three commonly used methods.

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

method

This is a network request based on the HTTP protocol for network communication, and the other two frameworks are also based on the HTTP protocol. HTTP protocol is a short connection-based protocol. The connection is disconnected after each interaction. HTTP requests are divided into two ways: GET and POST. GET requests are relatively simple. You only need to use the resource path of the stitching request after the URL, such as inputting the address of the anime keyword in Baidu Pictures.

/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 the index? There are many & connected projects followed by, this & represents the search conditions, and what does the last word=%E5%8A%A8%E6%BC%AB mean?

It is the input two words "animation", which is the byte encoded by UTF-8. A Chinese character will be composed into three bytes, which represents one byte in hexadecimal.

From this we can also see a limitation of GET requests, that is, they cannot pass Chinese and are not suitable for large-scale data submissions.

POST has no such limitation, and its security is higher than GET requests. In summary, it is to use GET for simple network requests, and POST requests for more complex ones that need to interact with the server.

Next is to send GET requests and POST requests.

GET Request

  //1. URL
    URL url = new URL("/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)();
    //3. set(GET)
    ("GET");
    //4. getInputStream
    InputStream is = ();
    //5. Parsing is, obtaining responseText, using buffered character stream here    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while((line=()) != null){
      (line);
    }
    //Get the response text    String responseText = ();

POST request

//1. URL
    URL url = new URL("/search/index");
    //2. HttpURLConnection
    HttpURLConnection conn = (HttpURLConnection)();
    //3. POST
    ("POST");
    //4. Content-Type, here is the fixed writing method, the type of content sent    ("Content-Type", "application/x-www-form-urlencoded");
    //5. output, here you need to remember to enable the output stream, write the parameters you want to add in with this output stream, and pass it to the server. This is the basic structure of the socket    (true);
    OutputStream os = ();
    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";
    //Be sure to convert your parameters into bytes, the encoding format is utf-8    (("utf-8"));
    ();
    //6. is
    InputStream is = ();
    //7. parse is and get responseText    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while((line=()) != null){
      (line);
    }
    //Get the response text    String responseText = ();

frame

GET Request

  //1. Create a RequestQueue, which is a request queue, which is equivalent to the processing of the message mechanism  private RequestQueue  mQueue = (this);
    //2. StringRequest
    String url = "";
    StringRequest req = new StringRequest(url, 
        new Listener<String>() {
          //Callback after the request is successful and executes in the main thread          public void onResponse(String responseText) {
            //Analyze json encapsulate result data            Gson gson = new Gson();
            //The Gson used here to parse JSON string            User result=(responseText,);
                      }
        }, new ErrorListener() {
          //Execute callback when a request error is encountered. Execute in the main thread          public void onErrorResponse(VolleyError error) {
            ();
          }
        });
  //Add req to the request queue, be sure to remember this step, otherwise it will be equivalent to not sending a request    (req);

POST request

private RequestQueue mQueue; 
//Post request must be implemented using commonRequest request  String url="";
  CommonRequest request = new CommonRequest(,url,new <String>() {
      public void onResponse(String response) {
        try {
        //This is the interface called after the request is successful, and use JSON tool to parse the data          JSONObject obj = new JSONObject(response);
        } catch (JSONException e) {
          ();
        }
      }
    },new () {
      public void onErrorResponse(VolleyError error) {
      }
    }){
      //If you use POST request, if you want to add parameters, you must rewrite 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 ("username",());        ("userAge",());
        ("userGender",());
("userSchool",());
        return resultMap;
      }
    };
    (request);
  }

3. Xutils3 framework

GET Request

//Step 1: Create a new request parameter objectRequestParams params=new RequestParams("?inm=2");
//Call the().get() method directly. Note here that x must be initialized in the global MyApplication before it can be used. The initialization method is (this)    ().get(params, new <String>() {
      @Override
      public void onCancelled(CancelledException arg0) {
      }
      @Override
      public void onError(Throwable arg0, boolean arg1) {
        ("", "http_on_error,Request for network data failed");
      }
      @Override
      public void onFinished() {
      }
      @Override
      public void onSuccess(String result) {
        ("", "The request data result is:"+result);
        Gson gson=new Gson();
        Result result=(result,);
        ("", "The loading result is:"+());
    }
    });

POST request

//The method is the same as GET, it is that simple. If the network request is successful, it will call back the success interface in the listener and directly process the data results.  RequestParams params=new RequestParams("");
    ("email", username);
    ("password", password);
    ().post(params, new CommonCallback<String>() {
      @Override
      public void onCancelled(CancelledException arg0) {
      }
      @Override
      public void onError(Throwable arg0, boolean arg1) {
        // Network errors will also prompt errors        (());
      }
      @Override
      public void onFinished() {
      }
      @Override
      public void onSuccess(String result) {
        Gson gson=new Gson();
      LoginResult loginResult=(result, );

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the relevant links below