一、java socket编程的介绍http://www.cnblogs.com/linzheng/archive/2011/01/23/1942328.html

二、URL、UrlConnection网络编程介绍

三、HTTP网络编程介绍

http协议-简介 http协议-C#获取网页源代码 http协议-多线程文件传输

四、 Web Service网络编程介绍

五、 android WebView网络编程介绍

实例代码-----------------------------------------------

 

 

 

服务器端模拟

MyServer.java

 

  1. package com.amaker.socket;  
  2.  
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5. import java.net.ServerSocket;  
  6. import java.net.Socket;  
  7. /**  
  8.  *   
  9.  * Socket 服务器,向客户端写Hello Android!  
  10.  */  
  11. public class MyServer {  
  12.     public static void main(String[] args) {  
  13.         try {  
  14.             ServerSocket server = new ServerSocket(8888);  
  15.             while(true){  
  16.                 Socket client = server.accept();  
  17.                 OutputStream out = client.getOutputStream();  
  18.                 String msg = "Hello Android!";  
  19.                 out.write(msg.getBytes());  
  20.                 client.close();  
  21.             }  
  22.         } catch (IOException e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.     }  

LoginServlet.java

 

  1. package com.amaker.http;  
  2.  
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.  
  11. /**  
  12.  *   
  13.  * 响应登录Servlet  
  14.  */  
  15. public class LoginServlet extends HttpServlet {  
  16.  
  17.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  18.             throws ServletException, IOException {  
  19.           
  20.         String username = request.getParameter("username");  
  21.         String password = request.getParameter("password");  
  22.         System.out.println(username+":"+password);  
  23.         response.setContentType("text/html");  
  24.         response.setCharacterEncoding("utf-8");  
  25.         PrintWriter out = response.getWriter();  
  26.         String msg = null;  
  27.         if(username!=null&&username.equals("admin")&&password!=null&&password.equals("1")){  
  28.             msg = "登录成功!";  
  29.         }else{  
  30.             msg = "登录失败!";  
  31.         }  
  32.         out.print(msg);  
  33.         out.flush();  
  34.         out.close();  
  35.     }  
  36.  
  37.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  38.             throws ServletException, IOException {  
  39.         doGet(request,response);  
  40.     }  
  41.  

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


<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

 

  1. package com.amaker.ch13;  
  2.  
  3. import android.app.ListActivity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.widget.ArrayAdapter;  
  8. import android.widget.ListView;  
  9.  
  10. import com.amaker.ch13.http.LoginActivity;  
  11. import com.amaker.ch13.socket.TestSocketActivity;  
  12. import com.amaker.ch13.url.TestURLActivity;  
  13. import com.amaker.ch13.webservice.TestWebServiceActivity;  
  14. import com.amaker.ch13.webservice.WeatherActivity;  
  15. import com.amaker.ch13.webview.TestWebViewActivity;  
  16.  
  17. public class MainActivity extends ListActivity {  
  18.     @Override  
  19.     public void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         // 菜单项数组  
  22.         String[] items = {"测试 Socket","测试URL、UrlConnection","测试 HTTP","测试 Web Service","天气预报","Test WebView"};  
  23.         // 将菜单项数组设置为ListView的列表项展示  
  24.         setListAdapter(new ArrayAdapter<String>(this,  
  25.                 android.R.layout.simple_list_item_1, items));  
  26.         getListView().setTextFilterEnabled(true);  
  27.     }  
  28.       
  29.     // 响应菜单项的单击事件  
  30.     protected void onListItemClick(ListView l, View v, int position, long id) {  
  31.         Intent intent = null;  
  32.         switch (position) {  
  33.         case 0:  
  34.             intent = new Intent(MainActivity.this,TestSocketActivity.class);  
  35.             startActivity(intent);  
  36.             break;  
  37.         case 1:  
  38.             intent = new Intent(MainActivity.this,TestURLActivity.class);  
  39.             startActivity(intent);  
  40.             break;  
  41.         case 2:  
  42.             intent = new Intent(MainActivity.this,LoginActivity.class);  
  43.             startActivity(intent);  
  44.             break;  
  45.         case 3:  
  46.             intent = new Intent(MainActivity.this,TestWebServiceActivity.class);  
  47.             startActivity(intent);  
  48.             break;  
  49.         case 4:  
  50.             intent = new Intent(MainActivity.this,WeatherActivity.class);  
  51.             startActivity(intent);  
  52.             break;  
  53.         case 5:  
  54.             intent = new Intent(MainActivity.this,TestWebViewActivity.class);  
  55.             startActivity(intent);  
  56.             break;  
  57.         }  
  58.     }  

AndroidManifest.xml

 

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  3.       package="com.amaker.ch13" 
  4.       android:versionCode="1" 
  5.       android:versionName="1.0"> 
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name"> 
  7.         <activity android:name=".MainActivity" 
  8.                   android:label="@string/app_name"> 
  9.             <intent-filter> 
  10.                 <action android:name="android.intent.action.MAIN" /> 
  11.                 <category android:name="android.intent.category.LAUNCHER" /> 
  12.             </intent-filter> 
  13.         </activity> 
  14.           
  15.         <activity android:name="com.amaker.ch13.http.LoginActivity"/> 
  16.           
  17.         <activity android:name="com.amaker.ch13.socket.TestSocketActivity"/> 
  18.           
  19.         <activity android:name="com.amaker.ch13.url.TestURLActivity"/> 
  20.           
  21.         <activity android:name="com.amaker.ch13.webservice.TestWebServiceActivity"/> 
  22.           
  23.         <activity android:name="com.amaker.ch13.webservice.WeatherActivity"/> 
  24.           
  25.         <activity android:name="com.amaker.ch13.webview.TestWebViewActivity"/> 
  26.  
  27.     </application> 
  28.     <uses-sdk android:minSdkVersion="3" /> 
  29.  
  30. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> 
  31. <uses-permission android:name="android.permission.INTERNET"></uses-permission> 
  32. </manifest> 

一、socket编程

TestSocketActivity.java

 

  1. 代码  
  2.  
  3. package com.amaker.ch13.socket;  
  4.  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.net.Socket;  
  8. import java.net.UnknownHostException;  
  9.  
  10. import android.app.Activity;  
  11. import android.os.Bundle;  
  12. import android.widget.TextView;  
  13. import com.amaker.ch13.R;  
  14. /**  
  15.  *   
  16.  * Android Socket 客户端接收服务器信息  
  17.  */  
  18. public class TestSocketActivity extends Activity {  
  19.     private TextView myTextView;  
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.socket);  
  24.         myTextView = (TextView)findViewById(R.id.msgTextView01);  
  25.         try {  
  26.             Socket socket = new Socket("192.168.1.101",8888);  
  27.             InputStream in = socket.getInputStream();  
  28.             byte[] buffer = new byte[in.available()];  
  29.             in.read(buffer);  
  30.             String msg = new String(buffer);  
  31.             myTextView.setText(msg);  
  32.         } catch (UnknownHostException e) {  
  33.             e.printStackTrace();  
  34.         } catch (IOException e) {  
  35.             e.printStackTrace();  
  36.         }  
  37.     }  

socket.xml

 

  1. 代码  
  2.  
  3. <?xml version="1.0" encoding="utf-8"?> 
  4. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  5.     android:orientation="vertical" 
  6.     android:layout_width="fill_parent" 
  7.     android:layout_height="fill_parent" 
  8.     > 
  9.       
  10.     <TextView   
  11.     android:text="等待接收服务器信息..."   
  12.     android:id="@+id/msgTextView01"   
  13.     android:layout_width="wrap_content"   
  14.     android:layout_height="wrap_content"></TextView> 
  15.       
  16. </LinearLayout> 

二、URL、UrlConnection编程

TestURLActivity.java

 

  1. 代码  
  2.  
  3. package com.amaker.ch13.url;  
  4.  
  5. import java.io.InputStream;  
  6. import java.net.URL;  
  7. import java.net.URLConnection;  
  8.  
  9. import android.app.Activity;  
  10. import android.graphics.Bitmap;  
  11. import android.graphics.BitmapFactory;  
  12. import android.os.Bundle;  
  13. import android.widget.ImageView;  
  14.  
  15. import com.amaker.ch13.R;  
  16. /**  
  17.  * 通过URL进行网络连接  
  18.  */  
  19. public class TestURLActivity extends Activity {  
  20.     private ImageView p_w_picpathView;  
  21.     @Override  
  22.     public void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.test_url);  
  25.         p_w_picpathView = (ImageView)findViewById(R.id.ImageView01);  
  26.           
  27.         String urlStr = "http://192.168.1.101:8080/Chapter_13_Networking_server/upload/zs.jpg";  
  28.           
  29.         try {  
  30.             URL url = new URL(urlStr);  
  31.             // 1. 直接使用URL获得输入流  
  32.             //InputStream in = url.openStream();  
  33.               
  34.             // 2. 获得URLconnection  
  35.             URLConnection conn = url.openConnection();  
  36.             InputStream in = conn.getInputStream();  
  37.               
  38.             // 3. 如果是HTTP协议可以使用HttpURLConnection  
  39.             //HttpURLConnection httpConn = (HttpsURLConnection)conn;  
  40.             //in = httpConn.getInputStream();  
  41.               
  42.             Bitmap bm = BitmapFactory.decodeStream(in);  
  43.               
  44.             p_w_picpathView.setImageBitmap(bm);  
  45.               
  46.         } catch (Exception e) {  
  47.             e.printStackTrace();  
  48.         }  
  49.     }  

test_url.xml

 

  1. 代码  
  2.  
  3. <?xml version="1.0" encoding="utf-8"?> 
  4. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  5.     android:orientation="vertical" 
  6.     android:layout_width="fill_parent" 
  7.     android:layout_height="fill_parent" 
  8.     > 
  9.  
  10.     <ImageView   
  11.         android:id="@+id/ImageView01"   
  12.         android:layout_width="wrap_content"   
  13.         android:layout_height="wrap_content"></ImageView> 
  14.  
  15. </LinearLayout> 

三、 HTTP编程

LoginActivity.java

 

  1. 代码  
  2.  
  3. package com.amaker.ch13.http;  
  4.  
  5. import java.io.UnsupportedEncodingException;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.  
  9. import org.apache.http.HttpResponse;  
  10. import org.apache.http.NameValuePair;  
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  12. import org.apache.http.client.methods.HttpPost;  
  13. import org.apache.http.impl.client.DefaultHttpClient;  
  14. import org.apache.http.message.BasicNameValuePair;  
  15. import org.apache.http.protocol.HTTP;  
  16. import org.apache.http.util.EntityUtils;  
  17.  
  18. import android.app.Activity;  
  19. import android.app.AlertDialog;  
  20. import android.content.DialogInterface;  
  21. import android.os.Bundle;  
  22. import android.view.View;  
  23. import android.view.View.OnClickListener;  
  24. import android.widget.Button;  
  25. import android.widget.EditText;  
  26.  
  27. import com.amaker.ch13.R;  
  28. public class LoginActivity extends Activity {  
  29.     /*  
  30.      * 声明使用到的Button和EditText视图组件  
  31.      */  
  32.     private Button cancelBtn,loginBtn;  
  33.     private EditText userEditText,pwdEditText;  
  34.       
  35.     @Override  
  36.     public void onCreate(Bundle savedInstanceState) {  
  37.         super.onCreate(savedInstanceState);  
  38.         setContentView(R.layout.http1);  
  39.         /*  
  40.          * 实例化视图组件  
  41.          */  
  42.         cancelBtn = (Button)findViewById(R.id.cancelButton);  
  43.         loginBtn = (Button)findViewById(R.id.loginButton);  
  44.           
  45.         userEditText = (EditText)findViewById(R.id.userEditText);  
  46.         pwdEditText = (EditText)findViewById(R.id.pwdEditText);  
  47.           
  48.         /*  
  49.          * 设置登录监听器  
  50.          */  
  51.         loginBtn.setOnClickListener(new OnClickListener() {  
  52.             @Override  
  53.             public void onClick(View v) {  
  54.                     String username = userEditText.getText().toString();  
  55.                     String pwd = pwdEditText.getText().toString();  
  56.                     login(username,pwd);  
  57.             }  
  58.         });  
  59.           
  60.         /*  
  61.          * 设置取消监听器  
  62.          */  
  63.         cancelBtn.setOnClickListener(new OnClickListener() {  
  64.             @Override  
  65.             public void onClick(View v) {  
  66.                 finish();  
  67.             }  
  68.         });  
  69.           
  70.  
  71.     }  
  72.       
  73.     /*  
  74.      * 定义一个显示提示信息的对话框  
  75.      */  
  76.     private void showDialog(String msg){  
  77.         AlertDialog.Builder builder = new AlertDialog.Builder(this);  
  78.         builder.setMessage(msg)  
  79.                .setCancelable(false)  
  80.                .setPositiveButton("确定", new DialogInterface.OnClickListener() {  
  81.                    public void onClick(DialogInterface dialog, int id) {  
  82.                    }  
  83.                });  
  84.         AlertDialog alert = builder.create();  
  85.         alert.show();  
  86.     }  
  87.     /*  
  88.      * 通过用户名称和密码进行查询,发送Post请求,获得响应结果。  
  89.      */  
  90.     private void login(String username,String password){  
  91.         // 1. 使用 HttpURLConnection 实现  
  92.         /*String urlStr = "http://192.168.1.101:8080/Chapter_13_Networking_server/servlet/LoginServlet?";  
  93.         String queryString = "username="+username+"&password="+password;  
  94.         urlStr+=queryString;  
  95.         try {  
  96.             URL url = new URL(urlStr);  
  97.             HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  98.                   
  99.             if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){  
  100.                 InputStream in = conn.getInputStream();  
  101.                 byte[] b = new byte[in.available()];  
  102.                 in.read(b);  
  103.                 String msg = new String(b);  
  104.                 showDialog(msg);  
  105.                 in.close();  
  106.             }  
  107.             conn.disconnect();  
  108.         } catch (Exception e) {  
  109.             showDialog(e.getMessage());  
  110.         }*/  
  111.         // 2. 使用 Apache HTTP 客户端实现  
  112.         String urlStr = "http://192.168.1.101:8080/Chapter_13_Networking_server/servlet/LoginServlet";  
  113.         HttpPost request = new HttpPost(urlStr);  
  114.         // 如果传递参数个数比较多的话,我们可以对传递的参数进行封装  
  115.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  116.         params.add(new BasicNameValuePair("username", username));  
  117.         params.add(new BasicNameValuePair("password", password));  
  118.         try {  
  119.             request.setEntity( new UrlEncodedFormEntity(params,HTTP.UTF_8));  
  120.             HttpResponse response = new DefaultHttpClient().execute(request);  
  121.             if(response.getStatusLine().getStatusCode()==200){  
  122.                 String msg = EntityUtils.toString(response.getEntity());  
  123.                 showDialog(msg);  
  124.             }  
  125.         } catch (Exception e) {  
  126.             e.printStackTrace();  
  127.         }  
  128.     }