Method of Android accessing network with HttpURLConnection

  • 2021-08-17 00:59:54
  • OfStack

1. HttpURLConnection accesses the network as GET:


HttpURLConnection connection = null;
try {
 URL url = new URL("https://www.xxx.com/");
 connection = (HttpURLConnection) url.openConnection();
 connection.setRequestMethod("GET");// Set the access mode to " GET " 
 connection.setConnectTimeout(8000);// Set the connection server timeout to 8 Seconds 
 connection.setReadTimeout(8000);// Set the read server data timeout to 8 Seconds 

 if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
  // Get the response from the server and convert the response data into a string for printing 
  InputStream in = connection.getInputStream();
  BufferedReader reader = new BufferedReader(new InputStreamReader(in));

  StringBuilder response = new StringBuilder();
  String line;
  while (null != (line = reader.readLine())) {
    response.append(line);
  }
  Log.d(TAG, response.toString());
 }
} catch (Exception e) {
 e.printStackTrace();
} finally {
 if (null!= connection) {
   connection.disconnect();
 }
}

2. HttpURLConnection accesses the network as POST:


HttpURLConnection connection = null;
  try{
   URL url = new URL("https://www.xxx.com/");
   connection = (HttpURLConnection) url.openConnection();

   connection.setRequestMethod("POST");
   connection.setConnectTimeout(8000);
   connection.setReadTimeout(8000);
   connection.setDoOutput(true);//  Use  URL  Connect for output 
   connection.setDoInput(true);//  Use  URL  Connect for input 
   connection.setUseCaches(false);//  Ignore cache 

   //  Create an output stream and write data 
   OutputStream outputStream = connection.getOutputStream();
   DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
   dataOutputStream.writeBytes("username=admin&password=888888");
   dataOutputStream.close();

   if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
    //  Processing data when responding correctly 
    StringBuffer response = new StringBuffer();
    String line;
    BufferedReader responseReader = 
      new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
    //  To process the response stream, it must be encoded with the output of the server response stream 1 To 
    while (null != (line = responseReader.readLine())) {
     response.append(line);
    }
    responseReader.close();
    Log.d(TAG, response.toString());
   }

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (null!= connection) {
    connection.disconnect();
   }
  }

Note:

1. HTTP access is not allowed on the main thread, otherwise an error will be reported. Therefore, the above operation should be done in a new thread.

2. 1 In general, HttpURLConnection. getResponseCode () = = 200 is used to determine whether the response is normal. If it is true, it will respond normally.

3. In Android 2.2 and below, HttpClient, Android 2.3 and above are used, HttpURLConnection is used, and Api related to HttpClient is discarded after Android 5.1. Therefore, the usage of HttpClient is no longer studied.

4. When submitting data in POST mode, each piece of data should be submitted in the form of key-value pair, and each piece of data should be submitted in the form of & Separate. For example, in the code above, dataOutputStream. writeBytes ("username = admin & password=888888 ");

5. StringBuilder and StringBuffer are used above. There is no special purpose, just by the way. StringBuilder is more efficient than StringBuffer on a single thread, but it is not thread safe.


Related articles: