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 webView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContent View (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) findView ById (R. id. test_url_main_wv); urlConnectionBtn. setOnClickListener (this); httpUrlConnectionBtn. setOnClickListener (this); httpClientBtn. setOnClickListener (this) ;}@ Override public 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 (); Indium UtStream 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 the ApacheHttp client to connect (important method) HttpClient client = new DefaultHttpClient (); // create an HttpGet object if it is submitted by Get, otherwise, the HttpPost object // POST is created and submitted in the form of HttpPost 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 Converts a set to an Entity object httpPost. setEntity (new UrlEncodedFormEntity (dataList); // GET Method for submission // HttpGet httpGet = new // HttpGet ("http: // 192.168.1.100: 8080/myweb/hello. jsp? Username = abc & pwd = 321 "); // get the corresponding message HttpResponse 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 (Cli EntProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}}} 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 httpUrlConnectionBtn; private Button httpClientBtn; private TextView showTextView; private WebView webView; @ Override protected void ongre Ate (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 = (T ExtView) findViewById (R. id. test_url_main_ TV _show); webView = (WebView) findViewById (R. id. test_url_main_wv); urlConnectionBtn. setOnClickListener (this); httpUrlConnectionBtn. setOnClickListener (this); httpClientBtn. setOnClickListener (this) ;}@ Override public 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. j Sp "); // 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 the ApacheHttp client to connect (important method) HttpClient client = new DefaultHttpClient (); // create an HttpGet object if it is submitted by Get, otherwise, the HttpPost object // POST is created and submitted in the form of HttpPost 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 Converts a set to an Entity object httpPost. setEntity (new UrlEncodedFormEntity (dataList); // GET Method for submission // HttpGet httpGet = new // HttpGet ("http: // 192.168.1.100: 8080/myweb/hello. jsp? Username = abc & pwd = 321 "); // get the corresponding message HttpResponse 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_httpurlconn Ection "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_conte Nt "/> <WebView android: id =" @ + id/test_url_main_wv "android: layout_width =" match_parent "android: layout_height =" match_parent "/> </LinearLayout> <? 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" /> <uses-permission android:name="android.permission.INTERNET" />