Use urlconnection, httpurlconnection, and httpclient to access network resources

Source: Internet
Author: User

The openconnection method of the URL returns a urlconnection, which indicates the communication connection between the application and the URL. The program can send a request to the URL through its instance to read the resources referenced by the URL.

The following is a simple example:

Activity:

Package COM. home. urlconnection; import Java. io. ioexception; import Java. io. inputstream; import java.net. httpurlconnection; import java.net. URL; import java.net. urlconnection; import Java. util. arraylist; import Java. util. list; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. client. clientprotocolexception; import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. entity. urlencodedformentity; import Org. apache. HTTP. client. methods. httppost; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. message. basicnamevaluepair; import Org. apache. HTTP. util. entityutils; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. webKit. webview; import android. widget. Button; import android. widget. textview; public class mainactivity extends activity implements onclicklistener {private button urlconnectionbtn; private button listener; private textview showtextview; private webview; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); init ();} Private void Init () {urlconnectionbtn = (button) findviewbyid (R. id. test_url_main_btn_urlconnection); httpurlconnectionbtn = (button) findviewbyid (R. id. test_url_main_btn_httpurlconnection); httpclientbtn = (button) findviewbyid (R. id. test_url_main_btn_httpclient); showtextview = (textview) findviewbyid (R. id. test_url_main_ TV _show); webview = (webview) findviewbyid (R. id. test_url_main_wv); urlconnection BTN. setonclicklistener (this); httpurlconnectionbtn. setonclicklistener (this); httpclientbtn. setonclicklistener (this) ;}@ overridepublic void onclick (view v) {If (V = urlconnectionbtn) {try {// directly use the urlconnection object to connect to URL url = new URL ("http: // 192.168.1.100: 8080/myweb/hello. JSP "); // obtain the urlconnection object urlconnection connection = URL. openconnection (); inputstream is = connection. getinputstream (); byte [] BS = New byte [1024]; int Len = 0; stringbuffer sb = new stringbuffer (); While (LEN = is. Read (BS ))! =-1) {string STR = new string (BS, 0, Len); sb. append (STR);} showtextview. settext (sb. tostring ();} catch (exception e) {e. printstacktrace () ;}}if (V = httpurlconnectionbtn) {// connect to try {URL url = new URL ("http: // 192.168.1.100: 8080/myweb/hello. JSP? Username = ABC "); // get the httpurlconnection object httpurlconnection connection = (httpurlconnection) URL. openconnection (); // set to get connection. setrequestmethod ("get"); If (connection. getresponsecode () = httpurlconnection. http_ OK) {// get the response message string message = connection. getresponsemessage (); showtextview. settext (Message) ;}} catch (exception e) {e. printstacktrace () ;}}if (V = httpclientbtn) {try {// use apachehttp (Important) httpclient client = new defaulthttpclient (); // create an httpget object if get is submitted, otherwise, the httppost object // post is created and submitted in the form of httppost = new httppost ("http: // 192.168.1.100: 8080/myweb/hello. JSP "); // If post is submitted, You can encapsulate the parameters in the set and pass list datalist = new arraylist (); datalist. add (New basicnamevaluepair ("username", "ABC"); datalist. add (New basicnamevaluepair ("PWD", "123"); // urlencodedformentity is used to convert a set to an entity object httppost. sete Ntity (New urlencodedformentity (datalist); // get Method for submission // httpget = new // httpget ("http: // 192.168.1.100: 8080/myweb/Hello. jsp? Username = ABC & Pwd = 321 "); // get the corresponding message httpresponse = client.exe cute (httppost); // get the message content httpentity entity = httpresponse. getentity (); // convert the message object to string content = entityutils. tostring (entity); // display in textview // showtextview. settext (content); // parse the webview of the Webpage Through webview. loaddatawithbaseurl (null, content, "text/html", "UTF-8", null); // parse the URL directly // webview. loadurl (URL);} catch (clientprotocolexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();}}}}

The URL used above is the Web application deployed on the author's local machine. It is not provided here. You can replace it with your own web application.
Layout XML:

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: Orientation = "vertical"> <button Android: id = "@ + ID/test_url_main_btn_urlconnection" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "Connect with urlconnection"/> <button Android: id = "@ + ID/test_url_main_btn_httpurlconnection" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "Connect with httpurlconnection"/> <button Android: id = "@ + ID/test_url_main_btn_httpclient" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "Connect with Apache client"/> <textview Android: id = "@ + ID/test_url_main_ TV _show" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"/> <webview Android: Id = "@ + ID/test_url_main_wv" Android: layout_width = "match_parent" Android: layout_height = "match_parent"/> </linearlayout>

Permission:

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

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.