Android Network: HTTP: Using HttpURLConnection to access webpages and obtain network image instances (source code)

Source: Internet
Author: User

As shown in the preceding figure, in addition to excellent TCP/UDP support for the transport layer, Android also provides good support for HTTP (Hypertext Transfer Protocol, there are two interfaces:

1. standard Java interface (java.net) ---- HttpURLConnection, which can implement simple URL-based request and response functions;

2. Apache interface (org. appache. http) ---- HttpClient, which is more powerful in use. Generally, this interface is used. However, this article will repeat the first interface.

Any interface has four basic functions: webpage access, image or file download, and file upload. This document demonstrates webpage access and image download. HttpURLConnection is inherited from the URLConnection class. It can be used to send and interface data of any type and length without knowing the length of the data stream in advance. You can set the request method to get, post, and timeout.

The following code is directly pasted. The purpose of the code is to access the Baidu homepage and obtain the html string returned by the code. The second is to download an image from a given URL and display it. A series of blog posts will be published to introduce HTTP-related knowledge.

Activity_main.xml

<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: id = "@ + id/parent_view" android: layout_width = "match_parent" android: layout_height = "match_parent" android: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/activity_vertical_margin" tools: context = ". mainActivity "> <FrameLayout android: layout_width =" match_parent "android: layout_height =" match_parent "> <TextView android: id =" @ + id/textview_show "android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "@ string/hello_world"/> <ImageView android: id = "@ + id/imagview_show" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_gravity = "center"/> </FrameLayout> <Button android: id = "@ + id/btn_visit_web" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignParentBottom = "true" android: layout_alignParentLeft = "true" android: text = "Access Baidu"/> <Button android: id = "@ + id/btn_download_img" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignParentBottom = "true" android: layout_toRightOf = "@ id/btn_visit_web" android: text = "Download image"/> </RelativeLayout>

MainActivity. java

Package org. yanzi. httpurlconnection; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import android. app. activity; import android. content. context; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. asyncTask; Import android. OS. bundle; import android. view. menu; import android. view. view; import android. view. viewGroup; import android. widget. button; import android. widget. imageView; import android. widget. progressBar; import android. widget. relativeLayout; import android. widget. textView; public class MainActivity extends Activity {Button visitWebBtn = null; Button downImgBtn = null; TextView showTextView = null; ImageVie W showImageView = null; String resultStr = ""; ProgressBar progressBar = null; ViewGroup viewGroup = null; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initUI (); visitWebBtn. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubshowImageView. setVisib Ility (View. GONE); showTextView. setVisibility (View. VISIBLE); Thread visitBaiduThread = new Thread (new VisitWebRunnable (); visitBaiduThread. start (); try {visitBaiduThread. join (); if (! ResultStr. equals ("") {showTextView. setText (resultStr) ;}} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}); downImgBtn. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubshowImageView. setVisibility (View. VISIBLE); showTextView. setVisibility (View. GONE); String imgUrl = "http://www.shixiu.net/d/fi Le/p/quiet "; new downimgasynctask(cmd.exe cute (imgUrl) ;}}) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true;} public void initUI () {showTextView = (TextView) findViewById (R. id. textview_show); showImageView = (ImageView) findViewById (R. id. ima Gview_show); downImgBtn = (Button) findViewById (R. id. btn_download_img); visitWebBtn = (Button) findViewById (R. id. btn_visit_web);}/*** get the response String of the specified URL * @ param urlString * @ return */private String getURLResponse (String urlString) {HttpURLConnection conn = null; // connection object InputStream is = null; String resultData = ""; try {URL url = new URL (urlString); // URL object conn = (HttpURLConnection) url. openConnection (); // use The URL opens a link conn. setDoInput (true); // allows the input stream to be downloaded. setDoOutput (true); // allows the output stream to be uploaded. setUseCaches (false); // do not use the buffer conn. setRequestMethod ("GET"); // use get request is = conn. getInputStream (); // get the input stream. In this case, the link InputStreamReader isr = new InputStreamReader (is); BufferedReader bufferReader = new BufferedReader (isr); String inputLine = ""; while (inputLine = bufferReader. readLine ())! = Null) {resultData + = inputLine + "\ n" ;}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {if (is! = Null) {try {is. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} if (conn! = Null) {conn. disconnect () ;}} return resultData;}/*** get the image from the specified URL * @ param url * @ return */private Bitmap getImageBitmap (String url) {URL imgUrl = null; Bitmap bitmap = null; try {imgUrl = new URL (url); HttpURLConnection conn = (HttpURLConnection) imgUrl. openConnection (); conn. setDoInput (true); conn. connect (); InputStream is = conn. getInputStream (); bitmap = BitmapFactory. decodeStream (is); is. close ();} catch (MalformedURLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return bitmap;} class VisitWebRunnable implements Runnable {@ Overridepublic void run () {// TODO Auto-generated method stubString data = getURLResponse ("http://www.baidu.com /"); resultStr = data ;}} class DownImgAsyncTask extends AsyncTask <String, Void, Bitmap >{@ Overrideprotected vo Id onPreExecute () {// TODO Auto-generated method stubsuper. onPreExecute (); showImageView. setImageBitmap (null); showProgressBar (); // display the progress bar prompt box} @ Overrideprotected Bitmap doInBackground (String... params) {// TODO Auto-generated method stubBitmap B = getImageBitmap (params [0]); return B ;}@ Overrideprotected void onPostExecute (Bitmap result) {// TODO Auto-generated method stubsuper. onPostExecute (result); if (re Sult! = Null) {dismissProgressBar (); showImageView. setImageBitmap (result) ;}}/ *** display progress bar in the middle of the parent Layout */private void showProgressBar () {progressBar = new ProgressBar (this, null, android. r. attr. progressBarStyleLarge); RelativeLayout. layoutParams params = new RelativeLayout. layoutParams (ViewGroup. layoutParams. WRAP_CONTENT, ViewGroup. layoutParams. WRAP_CONTENT); params. addRule (RelativeLayout. CENTER_IN_PARENT, RelativeLayo Ut. TRUE); progressBar. setVisibility (View. VISIBLE); Context context = getApplicationContext (); viewGroup = (ViewGroup) findViewById (R. id. parent_view); // MainActivity. this. addContentView (progressBar, params); viewGroup. addView (progressBar, params);}/*** hide progress bar */private void dismissProgressBar () {if (progressBar! = Null) {progressBar. setVisibility (View. GONE); viewGroup. removeView (progressBar); progressBar = null ;}}}

In AndroidManifest. xml, remember to add the network access permission:

<Uses-permission android: name = "android. permission. INTERNET"/>


Note:

1. To use HttpURLConnection, first instantiate a URL object and instantiate the HttpURLConnection object through the openConnection of the URL. Then set the parameters. Note that no connection is established at this time. The actual connection occurs when the conn. getInputStream clause is obtained, which is the same as that of TCP Socket. It is not blocked in ServerSocket. accept (), but is blocked in obtaining the stream. Therefore, all parameters should be set before obtaining the stream.

2. Get and POST access to the server. For the differences, see link 1 and link 2.

3. [all network operations after Android4.0 cannot be performed on the main thread!] The code in this article uses Thread when obtaining the webpage response string and AsyncTask when downloading the image. Obviously, AsyncTask is more important. In onPreExecute and onPostExecute, you can take the lead in thread UI.

4. When obtaining the webpage string, the Thread is used. join function, which will block the join operation in onClick until the Thread run is executed. Therefore, we should avoid this during actual development. The solution is to use Thread + Handle or AsyncTask. In fact, the latter is the encapsulation of the former.

5. Accessing images is relatively simple. You can use BitmapFactory to parse the input stream directly.

6. showProgressBar () and dismissProgressBar () are used to show and hide the prompt box when the image is downloaded.

Running effect:

Initial interface:



After you press to access Baidu:



After you click Download image:


-------------------------------- This article is original. For more information, see Author: yanzi1225627.

Source code download link: http://download.csdn.net/detail/yanzi1225627/7104645


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.