Android-network interaction client requests server resources

Source: Internet
Author: User

Recently, my work was not satisfactory, my feelings were not satisfactory, and I felt that everything was not going well. I spent some time on Android. Recently, I want to create an APK, which mainly involves network applications, so I also began to learn about modules that I didn't discuss before.

What we need to implement today is actually very simple. We can obtain a file on the server through the network (which can be txt, PNG, MP3, and so on). Because we used to develop C #, we started to work on it, simulating a server and obtaining a server's resource through a URL is as simple as this, so everyone should never be scared. There are no post requests, no get requests, that is, directly obtaining without verification, all these post and get requests are not involved.

Three interfaces are provided for implementing network connection in Android:

1. Standard java.net. * interface

2. org. Apache. * interface

3. android.net. * interface

My example is to use the first interface to download a TXT file from the server. We need to implement this function through several steps.

1. Create a file in sdcard and save the network stream as the final text file of TXT.

2. Implement network connection, get network stream, and save it to the TXT file in sdcard

3. Create a thread to download the server TXT file

4. simulate a Web Server (C #)

Step 1: Verify the sdcard status (whether it is loaded and can be read and written), obtain the (new) file directory, create a TXT file, and initialize a fileoutputstream object, it is the key link between data streams and files, as well as sdcard operation permissions.

Reference: http://tdq222.javaeye.com/blog/701962 code:

Code

 File dir = NULL;
File file = NULL;
If (environment. getexternalstoragestate (). Equals (environment. media_mounted )){
Log. V ("tag", "--------- Create File ");
// Obtain the sdcard directory
Dir = environment. getexternalstoragedirectory ();
// Create a file in the specified directory
File = new file (Dir, "test.txt ");
}
Fileoutputstream Fos = NULL;
Try {
Fos = new fileoutputstream (File );
} Catch (filenotfoundexception E1 ){
// Todo auto-generated Catch Block
E1.printstacktrace ();
}

 

Code

 <! -- Create and delete file permissions in sdcard -->
<Uses-Permission Android: Name = "android. Permission. mount_unmount_filesystems"/>
<! -- Write data to sdcard -->
<Uses-Permission Android: Name = "android. Permission. write_external_storage"/>

Step 2: Create a URL Connection object, configure the connection attributes (whether to read, connection timeout, and read timeout), and open the connection to obtain the data stream and save it to the file, you also have the network connection permission. Reference: http://java-cofi.javaeye.com/blog/734185 code:

Code

 // Cache
Byte [] BF = new byte [8192];
Int current = 0;
Try {
// Create a URL object
URL url = new URL (SPEC); // SPEC: Resource connection address
Httpurlconnection connect = (httpurlconnection) URL. openconnection ();
// Download HTTP resources from the server and set the read permission
Connect. setdoinput (true );
//// Upload the resource to the server and set the write permission
// Connect. setdooutput (true );
// Set the timeout value for connecting to the server
Connect. setconnecttimeout (5*1000 );
// Set the time-out for reading data from the server
Connect. setreadtimeout (30*1000 );
// Obtain the network connection status code
Int code = connect. getresponsecode ();
// Determine whether the connection is successful (httpurlconnection. http_ OK = 200, 0-are normal)
If (code = httpurlconnection. http_ OK ){
//// Open the connection to obtain the resource (it does not matter if you do not write it, call getinputstream () will open the connection by default // connect. Connect ();
Inputstream is = connect. getinputstream ();
Bufferedinputstream Bis = new bufferedinputstream (is );
While (current = bis. Read (BF ))! =-1 ){
FOS. Write (Bf, 0, current );
}
Bis. Close ();
FOS. Close ();
// Disconnect
Connect. Disconnect ();
}

} Catch (malformedurlexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}

 

Code

 <! -- Create and delete file permissions in sdcard -->
<Uses-Permission Android: Name = "android. Permission. mount_unmount_filesystems"/>
<! -- Write data to sdcard -->
<Uses-Permission Android: Name = "android. Permission. write_external_storage"/>

The third step is to prevent the main UI from being blocked when resources are downloaded.

Code

 Private handler = new handler (){
Public void handlemessage (Message MSG ){
// Prompt that the download is complete
If (msg. What = 1 ){
Toast. maketext (main. This, "Down succes", Toast. length_short). Show ();
} Else {
Toast. maketext (main. This, "Down fail", Toast. length_short). Show ();
}
Super. handlemessage (MSG );
}
};

@ Override
Public void onclick (view v ){
// Todo auto-generated method stub
Log. V ("tag", "------------ onclick ");
// Enable the download thread
Thread thread = new thread (New downthread ());
Thread. Start ();
}

Class downthread implements runnable {

@ Override
Public void run (){
// Todo auto-generated method stub
// Download resources
Download ();
Message MSG = new message ();
MSG. What = 1;
Handler. sendmessage (MSG );
}
}

Step 4 is simple. It is OK to create a new website and provide a link, for example, http: // localhost: 7643/website1/data/test.txt. But pay attention to the following:

Extract the token and open it.

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.