Android implements network programming through HttpURLConnection and HttpClient interfaces

  • 2020-06-15 10:09:32
  • OfStack

The HttpURLConnection and HttpClient interfaces provided in Android can be used to develop HTTP programs. Here are some lessons from learning.

1. HttpURLConnection interface

The first thing to be clear is the difference between the POST and GET requests in the Http communication. GET can get static pages, or it can pass parameters to the server after the URL string. The arguments to the POST method are placed in the Http request. Therefore, before programming, you should first specify the request method to use, and then select the appropriate programming method based on the method used. HttpURLConnection is inherited from the URLConnection class and both are abstract classes. Its object is obtained mainly through openConnection method of URL. The creation method is shown in the following code:


URL url = new URL("http://www.xxx.com/index.jsp?type=231");
HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();

The requested properties can be set in the following ways:


// Set up the input and output streams
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
// Set the request mode to POST
urlConn.setRequestMethod("POST");
//POST The request cannot be cached
urlConn.setUseCaches(false);
urlConn.disConnection();

HttpURLConnection USES GET by default, as shown in the following code:


HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
while (((inputLine = buffer.readLine()) != null)) {
    resultData += inputLine + "\n";
}
in.close();
urlConn.disconnect();

If you want to use POST mode, you need the setRequestMethod setting. The code is as follows:


String httpUrl = "http://www.xxx.com/getUser.jsp";
String resultData = "";
URL url = null;
try {
    url = new URL(httpUrl);
} catch (MalformedURLException e) {
    Log.e(DEBUG_TAG, "MalformedURLException");
}
if (url != null) { 
    try {
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 
        // Because this is post request , Settings need to be set to true 
        urlConn.setDoOutput(true); 
        urlConn.setDoInput(true);
        urlConn.setRequestMethod("POST"); // Settings to POST way   
        urlConn.setUseCaches(false); 
        urlConn.setInstanceFollowRedirects(true);
        urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
        // These configurations must be in place connect And before I did that,  
        // Here's the thing to notice connection.getOutputStream It's implicitly going to happen connect .  
        urlConn.connect(); 
        
        // DataOutputStream flow
        DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
        String content = "name=" + URLEncoder.encode(" zhang 3", "GB2312");   
        out.writeBytes(content);  
        out.flush();
        out.close();
    } catch(Exception e) {
        //
    }
}

2. HttpClient interface

The HTTP operation can also be performed using the HttpClient interface provided by Apache. The operation for the GET and POST request methods is different. The operation code example of GET method is as follows:


String httpUrl = "http://www.xxx.com/getUser.jsp?par=123"; 
// HttpGet Connection object  
HttpGet httpRequest = new HttpGet(httpUrl);  
HttpClient httpclient = new DefaultHttpClient(); 
HttpResponse httpResponse = httpclient.execute(httpRequest); 
// The request is successful  
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
    // Gets the returned string  
    String strResult = EntityUtils.toString(httpResponse.getEntity()); 
    mTextView.setText(strResult); 
} else { 
    mTextView.setText(" Request error !"); 
}

When using the POST method for parameter passing, you need to use NameValuePair to hold the parameters to be passed. In addition, you need to set the character set to be used. The code is as follows:


String httpUrl = "http://www.xxx.com/getUser.jsp";   
HttpPost httpRequest = new HttpPost(httpUrl);
List<NameValuePair> params = new ArrayList<NameValuePair>();   
params.add(new BasicNameValuePair("userId", "123")); 
HttpEntity httpentity = new UrlEncodedFormEntity(params, "GB2312"); // Set the character set
httpRequest.setEntity(httpentity);
// Get default HttpClient 
HttpClient httpclient = new DefaultHttpClient(); 
// achieve HttpResponse 
HttpResponse httpResponse = httpclient.execute(httpRequest); 
//HttpStatus.SC_OK Indicates successful connection  
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
    // Gets the returned string  
    String strResult = EntityUtils.toString(httpResponse.getEntity()); 
    mTextView.setText(strResult); 
} else { 
    mTextView.setText(" Request error !"); 
}

HttpClient is actually some encapsulation of the methods provided by Java. The input-output stream operation in HttpURLConnection is encapsulated by the interface 1 into HttpPost(HttpGet) and HttpResponse, thus reducing the operation complexity.

This is the end of this article, I hope you enjoy it.


Related articles: