Android Getting Started note-network communication-HttpURLConnection

Source: Internet
Author: User

There are many ways to communicate with remote servers in Android, and today we describe using the HTTP protocol to get data from a remote server.

In Android, you can use three interfaces and servers for HTTP communication:

1. Java standard interface: java.net.*;

2. Apathe interface: Org. apache. http. *;

3. Android interface: android.net.*;

Today we introduce the standard Java interface, and we will introduce the following:

1. Get the network HTML file using the Get method

2. Get the network HTML file using the Post method

3. Use the Get method to get a network picture and save it to a local

Because the code is more, I directly paste the key part, the article finally attached the project compress package file:


Code article:

1. Get the network HTML file using the Get method:

Call:

Btn_get.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {gettoopenurl ("http//" + Domin + ":" + port+ "/web1/login2.jsp?par1=10086&par2=199");});
Method:

Use the Get method to get the data private void Gettoopenurl (string urladdr) {try {string resultdata = ""; URL url = new URL (urladdr), if (URL! = null) {httpurlconnection connection = (httpurlconnection) url.openconnection (); Conne Ction.setconnecttimeout (+ 5); InputStreamReader in = new InputStreamReader (Connection.getinputstream ()); BufferedReader buffer = new BufferedReader (in); String inputline = Null;while ((inputline = Buffer.readline ()) = null) {Resultdata + = inputline + "\ n";} In.close (); Buffer.close (); Connection.disconnect (); Mtv.settext (Resultdata! = ""? Resultdata: "Read content is null");}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}
Steps to use:

(1) Initializes a URL object, which is the server address to be accessed. Domin and PORT define two static variables (below), after stitching: "http://192.168.1.19:8080/Web1/login2.jsp?par1=10086?par2=199", If you have studied JSP should know that here will pass two parameters past, and then the server JSP file can be processed (this does not introduce)

private static final String Domin = "192.168.1.19";
private static final String PORT = "8080";

(2) Call Url.openconnection () to get a HttpURLConnection object, which is the link between us and the server.

(3) The return stream of the server (the HTML file we requested) can then be obtained via Conn.getinputstream ()

(4) Parsing stream data (here we use the Resultdata string to keep the acquired HTML down and finally agree to the TextView.) Here we use Bufferreader to be able to read the HTML file in one line, keeping the original format of HTML.


2. Use the Post method to get the HTML file:

Call:

Btn_post.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {posttoopenurl ("HTTP/ "+ Domin +": "+ port+"/web1/login3.jsp ");}});

Method:

//use the Post method to request data private void Posttoopenurl (String urladdr) {string resultdata = ""; try { URL url = new URL (urladdr); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setdoinput (true); Conn.setdooutput (true); Conn.setrequestmethod ("POST"); Conn.setusecaches (true); Conn.setrequestproperty ("Content-type", "application/ X-www-form-urlencoded "), Conn.connect ();D ataoutputstream out = new DataOutputStream (Conn.getoutputstream ()); String content = "par=" + urlencoder.encode ("ABCDEFG", "gb2312"); out.writebytes (content); Out.flush (); Out.close (); BufferedReader buffer = new BufferedReader (New InputStreamReader (Conn.getinputstream ())); String inputline = Null;while ((inputline = Buffer.readline ()) = null) {Resultdata + = inputline + "\ n";} Buffer.close (); Conn.disconnect (); Mtv.settext (resultdata! = null? Resultdata: "Get data null");} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}} 
It is important to note that when using post to send a request, the requested parameter fields are not stitched directly behind the address, and the parameters should be written in the request stream. And the Post method is more secure, you can set more parameters, the amount of data can be transferred than get large, about the difference between post and get please refer to other information.

Steps to use:

(1) Initializing the URL object

(2) Call Url.openconnection () to get the HttpURLConnection object

(3) Set Input output: Conn.setdoinput (True); Conn.setdooutput (True)

(4) The Set request mode is Post:conn.setRequestMethod ("post");

(5) Set character encoding format content-type:conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");

(6) Then call Conn.connect (); Link server, open channel

(7) Then initialize the parameters and use writebytes (content); Want the server to send the request. Here is the parameter set to the stream sent to the server, the parameters equivalent to:? PAR=ABCDEFG

DataOutputStream out = new DataOutputStream (Conn.getoutputstream ()); String content = "par=" + urlencoder.encode ("ABCDEFG", "gb2312"); out.writebytes (content); Out.flush (); Out.close ();
(8) After sending the request, the receiving server returns the data, and the previous get gets the same server data.

You will find that when you use Get and post, it is different when you send data, the others are the same.


3. Get the network picture using the Get method:

If you run an instance you will find that the HTML we get is actually a text file, and TXT is the same, then if we want to get the image on the server, the image storage format slightly different is the binary storage, but for us is a stream, so in the process, We just need to convert the input into bitmap to get the picture.

Call:

Btn_getpicture.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {Bitmap picture = Getnetbitmap ("/http" + Domin + ":" + port+ "/web1/img.jpg"); if (null! = picture) {img_picture.setimagebitmap (picture); Savejpgbitmaptolocal (picture, "/sdcard/", String.Format (                     "portrait_%d" + ". jpg", system.cu Rrenttimemillis ()));} else {showtoast ("Get network picture Failed");}});

Method:

Get network picture private Bitmap Getnetbitmap (String mapurl) {Bitmap netpicture = null; HttpURLConnection conn;inputstream is;try {URL url = new URL (mapurl); conn = (httpurlconnection) url.openconnection (); Conn.setdoinput (true); is = Conn.getinputstream (), netpicture = Bitmapfactory.decodestream (is); Is.close (); Conn.disconnect ();} catch (Malformedurlexception e) {e.printstacktrace ();} catch (FileNotFoundException E1) {e1.printstacktrace ();} catch ( IOException e) {e.printstacktrace ();} return netpicture;}
We can see that the processing method is exactly the same as get, just after we get the input stream is, we convert it directly to bitmap.

Another way to invoke the call section is to save the captured picture to Local:

Save JPG image to local private void savejpgbitmaptolocal (Bitmap Bitmap, String path,string filename) {File File = new file (Path, fil ename); OutputStream os;try {os = new FileOutputStream (file); bitmap.compress (compressformat.jpeg, OS); Os.flush () ; Os.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}

Well, the example is complete, here are a few things to note:

If you run the instance get unsuccessful, there may be several reasons for this:

1. Look at the server startup Wood has

2. server address, port number

3. The file directory is correct under the server

4.192.168.1.19 is the local LAN address, do not use 127.0.0.1 here, because the phone simulator and its own local servers are occupied by this exchange-return address

Run:


Download Source Address:

http://download.csdn.net/detail/u013647382/8266051


Android Getting Started note-network communication-HttpURLConnection

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.