一、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
- 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="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
- 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 p_w_picpathView;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.test_url);
- p_w_picpathView = (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);
- p_w_picpathView.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();
- }
- }
- }