一、java socket编程的介绍
二、URL、UrlConnection网络编程介绍
三、HTTP网络编程介绍
四、 Web Service网络编程介绍
五、 android WebView网络编程介绍
实例代码-----------------------------------------------
服务器端模拟
MyServer.java
代码
package com.amaker.socket; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * * Socket 服务器,向客户端写Hello Android! */ public class MyServer { public static void main(String[] args) { try { ServerSocket server = new ServerSocket( 8888 ); while ( true ){ Socket client = server.accept(); OutputStream out = client.getOutputStream(); String msg = " Hello Android! " ; out.write(msg.getBytes()); client.close(); } } catch (IOException e) { e.printStackTrace(); } }}
LoginServlet.java
代码
package com.amaker.http; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * 响应登录Servlet */ public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter( " username " ); String password = request.getParameter( " password " ); System.out.println(username + " : " + password); response.setContentType( " text/html " ); response.setCharacterEncoding( " utf-8 " ); PrintWriter out = response.getWriter(); String msg = null ; if (username != null && username.equals( " admin " ) && password != null && password.equals( " 1 " )){ msg = " 登录成功! " ; } else { msg = " 登录失败! " ; } out.print(msg); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="" xmlns:xsi="" xsi:schemaLocation=" "> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.amaker.http.LoginServlet</servlet-class> </servlet><servlet-mapping>
<servlet-name>LoginServlet</servlet-name> <url-pattern>/servlet/LoginServlet</url-pattern> </servlet-mapping></web-app>
android客户端
MainActivity.java
代码
package com.amaker.ch13; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import com.amaker.ch13.http.LoginActivity; import com.amaker.ch13.socket.TestSocketActivity; import com.amaker.ch13.url.TestURLActivity; import com.amaker.ch13.webservice.TestWebServiceActivity; import com.amaker.ch13.webservice.WeatherActivity; import com.amaker.ch13.webview.TestWebViewActivity; public class MainActivity extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); // 菜单项数组 String[] items = { " 测试 Socket " , " 测试URL、UrlConnection " , " 测试 HTTP " , " 测试 Web Service " , " 天气预报 " , " Test WebView " }; // 将菜单项数组设置为ListView的列表项展示 setListAdapter( new ArrayAdapter < String > ( this , android.R.layout.simple_list_item_1, items)); getListView().setTextFilterEnabled( true ); } // 响应菜单项的单击事件 protected void onListItemClick(ListView l, View v, int position, long id) { Intent intent = null ; switch (position) { case 0 : intent = new Intent(MainActivity. this ,TestSocketActivity. class ); startActivity(intent); break ; case 1 : intent = new Intent(MainActivity. this ,TestURLActivity. class ); startActivity(intent); break ; case 2 : intent = new Intent(MainActivity. this ,LoginActivity. class ); startActivity(intent); break ; case 3 : intent = new Intent(MainActivity. this ,TestWebServiceActivity. class ); startActivity(intent); break ; case 4 : intent = new Intent(MainActivity. this ,WeatherActivity. class ); startActivity(intent); break ; case 5 : intent = new Intent(MainActivity. this ,TestWebViewActivity. class ); startActivity(intent); break ; } }}
AndroidManifest.xml
代码
<? xml version="1.0" encoding="utf-8" ?> < manifest xmlns:android ="http://schemas.android.com/apk/res/android" package ="com.amaker.ch13" android:versionCode ="1" android:versionName ="1.0" > < application android:icon ="@drawable/icon" android:label ="@string/app_name" > < activity android:name =".MainActivity" android:label ="@string/app_name" > < intent-filter > < action android:name ="android.intent.action.MAIN" /> < category android:name ="android.intent.category.LAUNCHER" /> </ intent-filter > </ activity > < activity android:name ="com.amaker.ch13.http.LoginActivity" /> < activity android:name ="com.amaker.ch13.socket.TestSocketActivity" /> < activity android:name ="com.amaker.ch13.url.TestURLActivity" /> < activity android:name ="com.amaker.ch13.webservice.TestWebServiceActivity" /> < activity android:name ="com.amaker.ch13.webservice.WeatherActivity" /> < activity android:name ="com.amaker.ch13.webview.TestWebViewActivity" /> </ application > < uses-sdk android:minSdkVersion ="3" /> < uses-permission android:name ="android.permission.ACCESS_NETWORK_STATE" ></ uses-permission > < uses-permission android:name ="android.permission.INTERNET" ></ uses-permission > </ manifest >
一、socket编程
TestSocketActivity.java
代码
package com.amaker.ch13.socket; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.UnknownHostException; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import com.amaker.ch13.R; /** * * Android Socket 客户端接收服务器信息 */ public class TestSocketActivity extends Activity { private TextView myTextView; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.socket); myTextView = (TextView)findViewById(R.id.msgTextView01); try { Socket socket = new Socket( " 192.168.1.101 " , 8888 ); InputStream in = socket.getInputStream(); byte [] buffer = new byte [in.available()]; in.read(buffer); String msg = new String(buffer); myTextView.setText(msg); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
socket.xml
代码
<? xml version="1.0" encoding="utf-8" ?> < LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android" android:orientation ="vertical" android:layout_width ="fill_parent" android:layout_height ="fill_parent" > < TextView android:text ="等待接收服务器信息..." android:id ="@+id/msgTextView01" android:layout_width ="wrap_content" android:layout_height ="wrap_content" ></ TextView > </ LinearLayout >
二、URL、UrlConnection编程
TestURLActivity.java
代码
package com.amaker.ch13.url; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.ImageView; import com.amaker.ch13.R; /** * 通过URL进行网络连接 */ public class TestURLActivity extends Activity { private ImageView imageView; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.test_url); imageView = (ImageView)findViewById(R.id.ImageView01); String urlStr = " http://192.168.1.101:8080/Chapter_13_Networking_server/upload/zs.jpg " ; try { URL url = new URL(urlStr); // 1. 直接使用URL获得输入流 // InputStream in = url.openStream(); // 2. 获得URLconnection URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); // 3. 如果是HTTP协议可以使用HttpURLConnection // HttpURLConnection httpConn = (HttpsURLConnection)conn; // in = httpConn.getInputStream(); Bitmap bm = BitmapFactory.decodeStream(in); imageView.setImageBitmap(bm); } catch (Exception e) { e.printStackTrace(); } }}
test_url.xml
代码
<? xml version="1.0" encoding="utf-8" ?> < LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android" android:orientation ="vertical" android:layout_width ="fill_parent" android:layout_height ="fill_parent" > < ImageView android:id ="@+id/ImageView01" android:layout_width ="wrap_content" android:layout_height ="wrap_content" ></ ImageView > </ LinearLayout >
三、 HTTP编程
LoginActivity.java
代码
package com.amaker.ch13.http; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; 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.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.amaker.ch13.R; public class LoginActivity extends Activity { /* * 声明使用到的Button和EditText视图组件 */ private Button cancelBtn,loginBtn; private EditText userEditText,pwdEditText; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.http1); /* * 实例化视图组件 */ cancelBtn = (Button)findViewById(R.id.cancelButton); loginBtn = (Button)findViewById(R.id.loginButton); userEditText = (EditText)findViewById(R.id.userEditText); pwdEditText = (EditText)findViewById(R.id.pwdEditText); /* * 设置登录监听器 */ loginBtn.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { String username = userEditText.getText().toString(); String pwd = pwdEditText.getText().toString(); login(username,pwd); } }); /* * 设置取消监听器 */ cancelBtn.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { finish(); } }); } /* * 定义一个显示提示信息的对话框 */ private void showDialog(String msg){ AlertDialog.Builder builder = new AlertDialog.Builder( this ); builder.setMessage(msg) .setCancelable( false ) .setPositiveButton( " 确定 " , new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); } /* * 通过用户名称和密码进行查询,发送Post请求,获得响应结果。 */ private void login(String username,String password){ // 1. 使用 HttpURLConnection 实现 /* String urlStr = " http://192.168.1.101 :8080/Chapter_13_Networking_server/servlet/LoginServlet?"; String queryString = "username="+username+"&password="+password; urlStr+=queryString; try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){ InputStream in = conn.getInputStream(); byte[] b = new byte[in.available()]; in.read(b); String msg = new String(b); showDialog(msg); in.close(); } conn.disconnect(); } catch (Exception e) { showDialog(e.getMessage()); } */ // 2. 使用 Apache HTTP 客户端实现 String urlStr = " http://192.168.1.101:8080/Chapter_13_Networking_server/servlet/LoginServlet " ; HttpPost request = new HttpPost(urlStr); // 如果传递参数个数比较多的话,我们可以对传递的参数进行封装 List < NameValuePair > params = new ArrayList < NameValuePair > (); params.add( new BasicNameValuePair( " username " , username)); params.add( new BasicNameValuePair( " password " , password)); try { request.setEntity( new UrlEncodedFormEntity(params,HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(request); if (response.getStatusLine().getStatusCode() == 200 ){ String msg = EntityUtils.toString(response.getEntity()); showDialog(msg); } } catch (Exception e) { e.printStackTrace(); } }}
http1.xml
代码
<? xml version="1.0" encoding="utf-8" ?> < LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android" android:orientation ="vertical" android:layout_width ="fill_parent" android:layout_height ="fill_parent" > < TableLayout android:layout_width ="fill_parent" android:layout_height ="fill_parent" android:stretchColumns ="1" > < TableRow > < TextView android:text ="用户名称:" android:id ="@+id/TextView" android:layout_width ="wrap_content" android:layout_height ="wrap_content" ></ TextView > < EditText android:text ="" android:id ="@+id/userEditText" android:layout_width ="fill_parent" android:layout_height ="wrap_content" ></ EditText > </ TableRow > < TableRow > < TextView android:text ="用户密码:" android:id ="@+id/TextView" android:layout_width ="wrap_content" android:layout_height ="wrap_content" ></ TextView > < EditText android:text ="" android:id ="@+id/pwdEditText" android:layout_width ="fill_parent" android:layout_height ="wrap_content" android:password ="true" ></ EditText > </ TableRow > < TableRow android:gravity ="right" > < Button android:text ="取消" android:id ="@+id/cancelButton" android:layout_width ="wrap_content" android:layout_height ="wrap_content" ></ Button > < Button android:text ="登陆" android:id ="@+id/loginButton" android:layout_width ="wrap_content" android:layout_height ="wrap_content" ></ Button > </ TableRow > </ TableLayout > </ LinearLayout >
四、Web Service编程
TestWebServiceActivity.java
代码
package com.amaker.ch13.webservice; import java.io.IOException; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.MarshalBase64; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.AndroidHttpTransport; import org.xmlpull.v1.XmlPullParserException; import android.app.Activity; import android.os.Bundle; public class TestWebServiceActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); String serviceNamespace = " http://tempuri.org/ " ; String serviceURL = " http://www.ayandy.com/Service.asmx " ; String methodName = " getWeatherbyCityName " ; SoapObject request = new SoapObject(serviceNamespace, methodName); PropertyInfo info = new PropertyInfo(); info.setName( " theCityName " ); info.setValue( " 北京 " ); PropertyInfo info2 = new PropertyInfo(); info2.setName( " theDayFlag " ); info2.setValue( " 1 " ); request.addProperty(info); request.addProperty(info2); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.bodyOut = request; ( new MarshalBase64()).register(envelope); AndroidHttpTransport ht = new AndroidHttpTransport(serviceURL); ht.debug = true ; try { ht.call( " http://tempuri.org/getWeatherbyCityName " , envelope); if (envelope.getResponse() != null ){ System.out.println(envelope.getResult()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
WeatherActivity.java
代码
package com.amaker.ch13.webservice; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; import com.amaker.ch13.R; /** * * 显示天气预报 */ public class WeatherActivity extends Activity { // 声明视图组件 private TextView displayTextView; private Spinner spinner; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.weather); // 实例化视图组件 displayTextView = (TextView) findViewById(R.id.displayTextView03); spinner = (Spinner) findViewById(R.id.citySpinner01); List < String > citys = WebServiceUtil.getCityList(); ArrayAdapter a = new ArrayAdapter( this , android.R.layout.simple_spinner_dropdown_item, citys); spinner.setAdapter(a); spinner.setOnItemSelectedListener( new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView <?> arg0, View arg1, int arg2, long arg3) { String msg = WebServiceUtil.getWeatherMsgByCity(spinner.getSelectedItem().toString()); displayTextView.setText(msg); } @Override public void onNothingSelected(AdapterView <?> arg0) { } }); }}
WebServiceUtil.java
代码
package com.amaker.ch13.webservice; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; 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.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.MarshalBase64; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.AndroidHttpTransport; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xmlpull.v1.XmlPullParserException; /** * * 天气预报工具类 */ public class WebServiceUtil { /* * 通过传递城市名称获得天气信息 */ public static String getWeatherMsgByCity(String cityName) { String url = " http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather " ; HttpPost request = new HttpPost(url); List < NameValuePair > params = new ArrayList < NameValuePair > (); params.add( new BasicNameValuePair( " theCityCode " , cityName)); params.add( new BasicNameValuePair( " theUserID " , "" )); String result = null ; try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); request.setEntity(entity); HttpResponse response = new DefaultHttpClient().execute(request); if (response.getStatusLine().getStatusCode() == 200 ) { result = EntityUtils.toString(response.getEntity()); return parse2(result); } } catch (Exception e) { e.printStackTrace(); } return null ; } /* * 使用ksoap,获得城市列表 */ public static List < String > getCityList() { // 命名空间 String serviceNamespace = " http://WebXml.com.cn/ " ; // 请求URL String serviceURL = " http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx " ; // 调用的方法 String methodName = " getRegionProvince " ; // 实例化SoapObject对象 SoapObject request = new SoapObject(serviceNamespace, methodName); // 获得序列化的Envelope SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; ( new MarshalBase64()).register(envelope); // Android传输对象 AndroidHttpTransport ht = new AndroidHttpTransport(serviceURL); ht.debug = true ; try { // 调用 ht.call( " http://WebXml.com.cn/getRegionProvince " , envelope); if (envelope.getResponse() != null ) { return parse(envelope.bodyIn.toString()); } } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null ; } /* * 对天气信息XML文件进行解析 */ private static String parse2(String str){ String temp; String[] temps; List list = new ArrayList(); StringBuilder sb = new StringBuilder( "" ); if (str != null && str.length() > 0 ){ temp = str.substring(str.indexOf( " <string> " )); temps = temp.split( " </string> " ); for ( int i = 0 ; i < temps.length; i ++ ) { sb.append(temps[i].substring( 12 )); sb.append( " \n " ); } } return sb.toString(); } /* * 对得到的城市XML信息进行解析 */ private static List < String > parse(String str) { String temp; List < String > list = new ArrayList < String > (); if (str != null && str.length() > 0 ) { int start = str.indexOf( " string " ); int end = str.lastIndexOf( " ; " ); temp = str.substring(start, end - 3 ); String[] test = temp.split( " ; " ); for ( int i = 0 ; i < test.length; i ++ ) { if (i == 0 ) { temp = test[i].substring( 7 ); } else { temp = test[i].substring( 8 ); } int index = temp.indexOf( " , " ); list.add(temp.substring( 0 , index)); } } return list; }}
weather.xml
代码
<? xml version="1.0" encoding="utf-8" ?> < LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android" android:orientation ="vertical" android:layout_width ="fill_parent" android:layout_height ="fill_parent" > < TextView android:text ="天气预报" android:id ="@+id/titleTextView01" android:layout_width ="wrap_content" android:layout_height ="wrap_content" ></ TextView > < LinearLayout android:orientation ="horizontal" android:layout_width ="fill_parent" android:layout_height ="wrap_content" > < TextView android:text ="请选择城市:" android:id ="@+id/cityTextView02" android:layout_width ="wrap_content" android:layout_height ="wrap_content" ></ TextView > < Spinner android:id ="@+id/citySpinner01" android:layout_width ="fill_parent" android:layout_height ="wrap_content" ></ Spinner > </ LinearLayout > < ScrollView android:id ="@+id/ScrollView01" android:layout_width ="wrap_content" android:layout_height ="wrap_content" > < TextView android:text ="@+id/displayTextView03" android:id ="@+id/displayTextView03" android:layout_width ="fill_parent" android:layout_height ="fill_parent" ></ TextView > </ ScrollView > </ LinearLayout >
五、WebView编程
TestWebViewActivity.java
代码
package com.amaker.ch13.webview; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import com.amaker.ch13.R; /** * 通过WebView浏览网络 */ public class TestWebViewActivity extends Activity { private WebView webView; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.test_webview); webView = (WebView)findViewById(R.id.mywebview); /* String url = " http://www.google.com "; webView.loadUrl(url); */ String html = "" ; html += " <html> " ; html += " <body> " ; html += " <a href=http://www.google.com>Google Home</a> " ; html += " </body> " ; html += " </html> " ; webView.loadData(html, " text/html " , " utf-8 " ); }}
test_webview.xml
代码
<? xml version="1.0" encoding="utf-8" ?> < LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android" android:orientation ="vertical" android:layout_width ="fill_parent" android:layout_height ="fill_parent" > < WebView android:id ="@+id/mywebview" android:layout_width ="fill_parent" android:layout_height ="fill_parent" /> </ LinearLayout >