Android Network Programming HttpUrlConnection HttpClient AsyncTask
1. HttpUrlConnection
A UrlConnection is often used to send and obtain data over the network. data can be of any type of length,HttpUrlConnectionIt is usually used to send and receive stream data with unknown length;
Create HttpURLConnection: Call Url. openConnection () and convert its type to HttpUrlConnection
CREATE Request: To include the most basic Url, you can set the Request Header (request data type, length, etc)
Set Request body): This is not required. If you need to set it, make sure setOutput (true );
Read Response: Return Response. The header contains data such as data type and length. You can use getInputStream () to read the body of the Response data. If no Response has no body, an Empty Stream is returned.
Disconnect: Call the disconnect () method of HttpUrlConnection
A simple example of using HttpUrlConnection: retrieving images remotely and displaying them in ImageView
ImageView imageView = (ImageView ). findViewById (R. id. imageview); URL url = new URL (http://www.jycoder.com/json/movies/1.jpg); HttpUrlConnection conn = (HttpUrlConnection) url. openConnection (); conn. connect (); try {InputStream in = conn. getInputStream (); // display the obtained image in ImageView Bitmap bitmap = BitmapFactory. decodeStream (in); imageView. setImageBitmap (BitmapFactory. decode (is);} finally {conn. disconnect ();}
The above is the basic usage of HttpUrlConnection, and some theme to be mastered:
Http Response error: If an error or exception is returned, the getInputStream () directly throws an exception. We can use getErrorStream (); to read the Response error message and getHeaderFields () to read the Response header;
Post Content: SetOutput (true) is required to send data to the server. For performance, if you know the size of your Post content, you can use setFixedLengthStreamingMode (int). If you do not know, you can use setChunkedStreamingMode (int );
HTTP Method: You can set it through setRequestMethod (String ).
Cookie and Cache: HttpUrlConnection has CookieManager and CookieHandler methods to set cookies. The HttpResponseCache class is provided for Cache. For more information, see HttpUrlConnection.
HttpResponseCache
2, HttpClient
Android has been deprecated since API 22. Use HttpUrlConnection whenever possible.
3. AsyncTask
AsyncTask is a mechanism for implementing asynchronous operations. We often need to update the UI, but the main thread cannot perform time-consuming operations. Otherwise, an error occurs. AsyncTask is used to perform background operations, no need to manually process the creation and execution of threads; it is often used to process someShort-term operationsIf you want to use the Service for a long time
Use AsyncTask:
Create a Task: We need to create a Task inherited from AsyncTask,
AsyncTask requires three parameters: Params, SS, and Result.:
Params indicates the parameters that need to be passed during task execution: new MyTask.exe cute (Params); Progress indicates the Progress of the task to be passed in the task. The relevant methods are publisProgress () and onUpdateProgress () result indicates the Result of the final Task execution. We also need to overwrite the four methods in AsyncTask:
OnPreExecute () Task is called before execution. It runs in the main thread (UI thread) and runs in the background thread of doInBackground (), such as creating the original progress bar view, time-consuming operations such as getting network data are all run in the onUpdateProgress () main thread to update the progress, and called back when the publishProgress () method is called in the doInBackground () method. OnPostExecute () is run in the main thread and called when the task is completed,
Tips: we can see that the four methods in AsyncTask only run in the doInBackground () real background thread. Therefore, some time-consuming operations are executed in it, while other methods run in the UI thread, update the UI view.
Execute a Task in the main thread: AsyncTask must be instantiated and executed in the main thread, and each AsyncTask must be executed only once.
Cancel a Task: AsyncTask can be canceled at any time by calling cancel (true.
Based on the above, let's do an exercise:
Create a project:
UseAsyncTask
InManifest.xml
Add network Permissions
Create a layout, which is used to display a movie image,
Complete
MainActivity
Public class MainActivity extends ActionBarActivity {private ImageView imageView; // image address private final String url = progress // display progress private ProgressDialog pDialog; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // used to display the progress pDialog = new ProgressDialog (this); pDialog. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); pDialog. setMessage (Loading ...); pDialog. setMax (100); imageView = (ImageView) findViewById (R. id. movie_image); // execute Task new imagedownloadtask(cmd.exe cute (url);} public class ImageDownloadTask extends AsyncTask
{@ Override protected void onPreExecute () {super. onPreExecute (); pDialog. show () ;}@ Override protected Bitmap doInBackground (String... urls) {HttpURLConnection connection = null; Bitmap bitmap = null; try {URL url = new URL (urls [0]); connection = (HttpURLConnection) url. openConnection (); InputStream in = new BufferedInputStream (connection. getInputStream (); bitmap = BitmapFactory. decodeStream (in); // get File stream size, used to update progress int length = connection. getContentLength (); int len = 0, total_length = 0, value = 0; byte [] data = new byte [1024]; while (len = in. read (data ))! =-1) {total_length + = len; value = (int) (total_length/(float) length) * 100); // call the update function, update Progress publishProgress (value) ;}} catch (IOException e) {e. printStackTrace ();} finally {if (connection! = Null) connection. disconnect () ;}return bitmap ;}@ Override protected void onProgressUpdate (Integer... values) {super. onProgressUpdate (values); pDialog. setProgress (values [0]);} @ Override protected void onPostExecute (Bitmap bitmap) {if (pDialog! = Null) pDialog. dismiss (); pDialog = null; // fill the Bitmap in the Imageview imageView. setImageBitmap (bitmap );}}}
Summary:
This part is simple ~, In fact, it is difficult to understand the UI thread and the application scenarios of AsyncTask and Service.