Android self-learning process-simple use of HttpURLConnection, androidhttpurl

Source: Internet
Author: User

Android self-learning process-simple use of HttpURLConnection, androidhttpurl

I learned OkHttp some time ago, but I still don't understand it enough. I just heard that HttpURLConnection is gradually moving closer to OkHttp, so I decided to play with HttpURLConnection. It's just that I have a lot of knowledge about this part on the Internet, so I can find it through the Demo. The predecessors planted trees, and those who came to the cold expressed their respect. Learning from others is an indispensable step in learning. Right, so this article reference from: http://blog.csdn.net/yanzi1225627/article/details/22222735

Http://lzyblog.com/2014/09/18/HttpClient%E5%92%8CHttpURLConnection%E7%9A%84%E4%BD%BF%E7%94%A8%E5%92%8C%E5%8C%BA%E5%88%AB-%E4%B8%8B/

 

In fact, better tutorials from the official website: http://developer.android.com/training/basics/network-ops/connecting.html

 

Of course, there will also be personal notes from beginners. This part of knowledge is not isolated, except for the use of HttpURLConnection, there are also inseparable threads and how to update the main UI. Finally, I suggest you start learning.

 

As always, first look at the image.

The layout seems simple, but here we use the FrameLayout layout method (set up the effect of superposition). Although it is not very common, Fragment must be a knowledge point that everyone will learn in the future.

<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" 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/plugin" tools: context = ". mainActivity "> <FrameLayout android: layout_width =" match_parent "android: layout_height =" match_parent "> <TextView android: id =" @ + id/textView "android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Show_message"/> <ImageView android: id = "@ + id/imageView" android: layout_width = "wrap_content" android: layout_height = "match_parent" android: layout_gravity = "center"/> </FrameLayout> <Button android: id = "@ + id/button01" 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/button02" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignParentBottom = "true" android: layout_alignParentRight = "true: text = "Download image"/> </RelativeLayout>

 

The following is the main logic code: the function is to obtain webpage information and download images through HttpUrlConnect.

Package com. ryan. httpurlconnectiondemo01; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. asyncTask; import android. support. v7.app. appCompatActivity; import android. OS. bundle; import android. view. menu; import android. view. menuItem; import android. view. view; import android. widget. button; import android. widget. imageView; import android. widget. textView; import java. io. buff EredReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL;/*** instance reference: http://blog.csdn.net/yanzi1225627/article/details/22222735 **/public class MainActivity extends AppCompatActivity implements View. onClickListener {private TextView textView; private ImageView image View; private Button webButton; private Button imgButton; String resultStr = ""; // private void initView () {textView = (TextView) findViewById (R. id. textView); imageView = (ImageView) findViewById (R. id. imageView); webButton = (Button) findViewById (R. id. button01); imgButton = (Button) findViewById (R. id. button02); webButton. setOnClickListener (this); imgButton. setOnClickListene R (this) ;}@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initView () ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. button01: // TODO: 15-9-10 get the webpage information textView. setVisibility (View. VISIBLE); imageView. setVisibility (View. GONE); // enable Thread visitWebThread = new Thread (new visitWebRunn Able (); visitWebThread. start (); try {// wait until the sub-thread in the multi-thread ends and then execute visitWebThread. join (); if (! ResultStr. equals ("") {textView. setText (resultStr) ;}} catch (InterruptedException e) {e. printStackTrace ();} break; case R. id. button02: // TODO: 15-9-10 get the network image textView. setVisibility (View. GONE); imageView. setVisibility (View. VISIBLE); String imgUrl = "http://pic.cnblogs.com/avatar/790633/20150727124352.png"; // AsyncTask () new downimgasynctask(.exe cute (imgUrl); break;} private class visitWebRu Nnable implements Runnable {@ Override public void run () {String date = getURlResponse ("http://www.baidu.com/"); resultStr = date ;}} private String getURlResponse (String s) {HttpURLConnection httpURLConnection = null; InputStream inputStream = null; String resultData = ""; try {URL url = new URL (s); // URl object httpURLConnection = (HttpURLConnection) url. openConnection (); // use a URl to open a link httpURLConn Ection. setDoInput (true); // allows the input stream to be downloaded. setDoOutput (true); // allows the output stream to be uploaded. setUseCaches (false); // do not use the httpURLConnection buffer. setRequestMethod ("GET"); // use get to request inputStream = httpURLConnection. getInputStream (); // get the input stream. In this case, the link BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (inputStream); String inputLine; while (inputLine = bufferedReader. read Line ())! = Null) {resultData = inputLine + resultData + "\ n" ;}} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {inputStream. close ();} catch (IOException e) {e. printStackTrace ();} httpURLConnection. disconnect ();} return resultData;} private class DownImgAsyncTask extends AsyncTask {// @ Override // protected void onPreExecute () {// super. onPreExecute (); // imageView. setImageBitmap (null); // showProgressBar (); // display the progress bar prompt box //} @ Override protected Object doInBackground (Object [] params) {Bitmap B = getImageBitmap (String. valueOf (params [0]); return B ;}@ Override protected void onPostExecute (Object o) {super. onPostExecute (o); imageView. setImageBitmap (Bitmap) o) ;}} private Bitmap getImageBitmap (String url) {URL imgUrl = null; Bitmap bitmap = null; try {imgUrl = new URL (url ); httpURLConnection httpURLConnection = (HttpURLConnection) imgUrl. openConnection (); httpURLConnection. setDoInput (true); httpURLConnection. connect (); InputStream inputStream = httpURLConnection. getInputStream (); bitmap = BitmapFactory. decodeStream (inputStream); inputStream. close ();} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return bitmap;} @ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. menu_main, menu); return true;} @ Override public boolean onOptionsItemSelected (MenuItem item) {// Handle action bar item clicks here. the action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest. xml. int id = item. getItemId (); // noinspection SimplifiableIfStatement if (id = R. id. action_settings) {return true;} return super. onOptionsItemSelected (item );}}

 

Here, the reconstructed code minus the showProgressBar () method of the original text, that is, the reality of the download progress bar.

Obtain webpage information:

We have seen the thread implementation method before.

Thread visitWebThread = new Thread(new visitWebRunnable());                visitWebThread.start();private class visitWebRunnable implements Runnable {        @Override        public void run() {        
        String date = getURlResponse("http://www.baidu.com/");

        resultStr = date;
} }

 

The web page information is printed through HpptURLConnect.

Private String getURlResponse (String s) {HttpURLConnection httpURLConnection = null; InputStream inputStream = null; String resultData = ""; try {URL url = new URL (s ); // URl object httpURLConnection = (HttpURLConnection) url. openConnection (); // use a URl to open a link httpURLConnection. setDoInput (true); // allows the input stream to be downloaded. setDoOutput (true); // allows the output stream to be uploaded. setUseCaches (false); // no buffer ht is used TpURLConnection. setRequestMethod ("GET"); // use get to request inputStream = httpURLConnection. getInputStream (); // get the input stream. In this case, the link BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (inputStream); String inputLine; while (inputLine = bufferedReader. readLine ())! = Null) {resultData = inputLine + resultData + "\ n" ;}} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {inputStream. close ();} catch (IOException e) {e. printStackTrace ();} httpURLConnection. disconnect ();} return resultData ;}

1. Create an HttpURLConnection object

URL url = new URL("xxxxxx"); URLConnection urlConnection = url.openConnection();HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
Ii. HttpURLConnection parameter settings

 

 

 

 

 

Forgive me. It's too good to write.

 

Update webpage Information

There is no way to update web page information, but to save the required informationIn the String type variable of resultStr, Directly update in the main UI Thread. Of course, the original author uses the Thread. join method to ensure information integrity.

The original author of this method also said,

 

 

About downloading images

The main difference between this and obtaining webpage information is: thread implementation

 String imgUrl = "http://pic.cnblogs.com/avatar/790633/20150727124352.png";                //AsyncTask()                new DownImgAsyncTask().execute(imgUrl);

 

 

Many methods can be implemented in AsyncTask. Here I first have a rough understanding of the functions of doInBackground and onPostExecute methods.

1. The params parameter runs through

2. The value returned by the doinbackground method, and the connection with onPostExecute.

 

I thought it would be difficult to get images. I didn't expect such a simple method:

bitmap = BitmapFactory.decodeStream(inputStream);

 

Another important thing is not to forget to add
<uses-permission android:name="android.permission.INTERNET"></uses-permission>


This is basically the end, and we will further understand the use of Handler or AsyncTask.
 

 

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.