This article describes the use of HttpURLConnection for network programming in Android development. Share it for your reference, as follows:
——HttpURLConnection
URLConnection can be used to exchange information with designated sites very conveniently. There is also a subclass under URLConnection: HttpURLConnection. HttpURLConnection has been improved on the basis of URLConnection, adding some convenient methods for operating HTTP resources.
setRequestMethod(String)
: Set the method to send requestsgetResponseCode()
: Get the server's response codegetResponseMessage()
: Get the server's response message
a) Get request code:
conn=(HttpURLConnection)(); ("GET"); (8000);//The number of milliseconds of connection timeout(8000);//Read the number of milliseconds of timeout
b) Post request code
conn=(HttpURLConnection)(); ("POST");
c) Close the connection
if(conn!=null)();
Steps to implement multi-threaded download:
a) Create URL object
b) Get the size of the resource pointed to by the specified URL object:getContentLength()
c) Create an empty file on the local disk of the same size as the network resource
d) Calculate the specified part of the network resource downloaded by each thread application
e) Create in turn, start multiple threads to download the specified part of the network resource
Pay attention to the required permissions:
<uses-permission android:name=".WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name=".MOUNT_UNMOUNT_FILESYSTEMS"/>
For more instructions on Android permission control, please refer toAndroid Manifest function and permission description
Here I will simply use HttpURLConnection to perform text parsing and image parsing
The programming steps are as follows:
1. Write the layout file first:
<LinearLayout xmlns:andro xmlns:tools="/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click" android:text="Loading pictures" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click2" android:text="Load text" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:/> </LinearLayout>
2. Implementation of text parsing in MainActivity:
//Text parsingpublic void click2(View view){ new Thread(){ public void run() { try { URL url2=new URL(""); HttpURLConnection conn=(HttpURLConnection) (); ("GET"); (8000); (8000); (); if(()==200){ InputStream inputStream=(); ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); byte[]b=new byte[512]; int len; while ((len=(b))!=-1) { (b,0,len); } String text=new String((),"UTF-8"); Message msg=(); =0x124; =text; (msg); } } catch (Exception e) { // TODO Auto-generated catch block (); } }; }.start(); }
The GET method is used here~ You can also use the POST method~
3. Implementation of image parsing in MainActivity:
//Picture Analysispublic void click(View view){ final File file=new File(getCacheDir(),""); if(()){ ("Use cache"); Bitmap bitmap=(()); (bitmap); }else{ new Thread(){ public void run() { try { URL url=new URL("http://192.168.207.1:8090/"); ("Using the Internet"); HttpURLConnection conn=(HttpURLConnection) (); ("GET"); (8000); (8000); (); if(200==()){ //Normal connection InputStream is=(); //Bitmap bitmap=(is); FileOutputStream fileOutputStream=new FileOutputStream(file); int len; byte[] b=new byte[1024]; while ((len=(b))!=-1) { (b,0,len); } (); Bitmap bitmap=(()); (); Message msg=(); =0x123; =bitmap; (msg); } } catch (Exception e) { // TODO Auto-generated catch block (); } }; }.start(); } }
This image parsing realizes the cache of the image. When you want to load the image again, you can get the image in the cached file, which can reduce the use of memory~
I put this image in this directory on the server side\apache-tomcat-7.0.37\webapps\upload. You can download this image from the server and save it in a file~
4. Finally, load the text and pictures
private Handler handler=new Handler(){ public void handleMessage( msg) { if(==0x123){ Bitmap bitmap=(Bitmap) ; (bitmap); } else if(==0x124){ String text=(String) ; (text); } }; };
I won't post the renderings anymore, just know how to write the code ~
The complete MainActivity code is as follows:
public class MainActivity extends Activity { private ImageView iv; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); iv=(ImageView) findViewById(); tv=(TextView) findViewById(); } private Handler handler=new Handler(){ public void handleMessage( msg) { if(==0x123){ Bitmap bitmap=(Bitmap) ; (bitmap); } else if(==0x124){ String text=(String) ; (text); } }; }; //Text parsing public void click2(View view){ new Thread(){ public void run() { try { URL url2=new URL(""); HttpURLConnection conn=(HttpURLConnection) (); ("GET"); (8000); (8000); (); if(()==200){ InputStream inputStream=(); ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); byte[]b=new byte[512]; int len; while ((len=(b))!=-1) { (b,0,len); } String text=new String((),"UTF-8"); Message msg=(); =0x124; =text; (msg); } } catch (Exception e) { // TODO Auto-generated catch block (); } }; }.start(); } //Picture Analysis public void click(View view){ final File file=new File(getCacheDir(),""); if(()){ ("Use cache"); Bitmap bitmap=(()); (bitmap); }else{ new Thread(){ public void run() { try { URL url=new URL("http://192.168.207.1:8090/"); ("Using the Internet"); HttpURLConnection conn=(HttpURLConnection) (); ("GET"); (8000); (8000); (); if(200==()){ //Normal connection InputStream is=(); //Bitmap bitmap=(is); FileOutputStream fileOutputStream=new FileOutputStream(file); int len; byte[] b=new byte[1024]; while ((len=(b))!=-1) { (b,0,len); } (); Bitmap bitmap=(()); (); Message msg=(); =0x123; =bitmap; (msg); } } catch (Exception e) { // TODO Auto-generated catch block (); } }; }.start(); } } }
Attached:Click here for the full example codeDownload this site。
For more information about Android related content, please check out the topic of this site:Android communication methods summary》、《Android development introduction and advanced tutorial》、《Android debugging skills and solutions to common problems》、《Android multimedia operation skills summary (audio, video, recording, etc.)》、《Summary of the usage of basic Android components》、《Android View View Tips Summary》、《Android layout layout tips summary"and"Android control usage summary》
I hope this article will be helpful to everyone's Android programming design.