第十七天 乐在其中-Android与远端之通过JSON访问SQLServer 2005数据库

时间:2022-03-10 22:52:31

           5月10日,中雨。“黑云翻墨未遮山, 白雨跳珠乱入船。卷地风来忽吹散, 望湖楼下水如天。”

       在SQLServer 2005创建数据库librarydb,供测试使用. 建立方法见第十一天博客。

      1、服务器端

          (1)工程视图

         第十七天 乐在其中-Android与远端之通过JSON访问SQLServer 2005数据库

                   (2)AndroidServlet.java

package json.sqlserver;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

@WebServlet("/AndroidServlet")
public class AndroidServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	static String driver = "net.sourceforge.jtds.jdbc.Driver";
	static String url = "jdbc:jtds:sqlserver://192.168.23.1:1433/librarydb";
	static String user = "sa";
	static String password = "sa";

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");

		List resultList = null;
		try {
			resultList = getData();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Gson gson = new Gson();
		String result = gson.toJson(resultList);
		PrintWriter out = response.getWriter();
		out.write(result);
		out.flush();
		out.close();
	}

	private List getData() throws Exception {
		List resultList = new ArrayList();
		Class.forName(driver);
		Connection conn = (Connection) DriverManager.getConnection(url, user,
				password);
		Statement statement = (Statement) conn.createStatement();
		String sql = null;
		sql = "select S_Name from student";
		ResultSet rs = statement.executeQuery(sql);
		while (rs.next()) {
			resultList.add(rs.getString("S_Name"));
		}

		return resultList;

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
            (3)运行http://192.168.23.1:8080/ServletForJsonSqlserver2005/AndroidServlet
          注意:IP:192.168.23.1:8080,是WIFI共享精灵设置的虚拟的无线网卡的IP,IP自然由虚拟的无线路由分配,使用手机连接,会自动给手机分配同一网段的IP:如:192.168.23.2

第十七天 乐在其中-Android与远端之通过JSON访问SQLServer 2005数据库

        2、手机端代码
          (1)工程视图

第十七天 乐在其中-Android与远端之通过JSON访问SQLServer 2005数据库

               (2)MainActivity.java

package com.androidjsonsqlserver;

import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

	JSONArray jArray;
	String result = null;
	InputStream is = null;
	StringBuilder sb = null;

	public static final String HTTPCustomer = "http://192.168.23.1:8080/ServletForJsonSqlserver2005/AndroidServlet";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button b1 = (Button) findViewById(R.id.button1);

		b1.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {

				EditText tv = (EditText) findViewById(R.id.editView);
				// http post
				try {

					HttpClient httpclient = new DefaultHttpClient();

					// HttpGet httpget = new HttpGet(HTTPCustomer);
					HttpPost httppost = new HttpPost(HTTPCustomer);
					HttpResponse response = httpclient.execute(httppost);

					int status = response.getStatusLine().getStatusCode();
					System.out.println("status=" + status);
					result = EntityUtils.toString(response.getEntity(), "UTF-8");
				} catch (Exception e) {
					e.printStackTrace();
				}

				try {
					Gson gson = new Gson();
					List<String> names = gson.fromJson(result,
							new TypeToken<List<String>>() {
							}.getType());

					StringBuffer str = new StringBuffer();

					for (String name : names) {

						str.append(name);
					}

					tv.setText(str);
				} catch (Exception e) {

					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}
         (3) main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="click" />

    <EditText
        android:id="@+id/editView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HI "
        android:textSize="30dip" />
</LinearLayout>
        (4) strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AndroidJsonSqlserver2005</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

</resources>
      (5) AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjsonsqlserver"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidjsonsqlserver.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>
    </application>
     <uses-permission android:name="android.permission.INTERNET"/>
</manifest>
             5、安卓模拟器运行结果
第十七天 乐在其中-Android与远端之通过JSON访问SQLServer 2005数据库

           6、手机运行结果-手机截屏

第十七天 乐在其中-Android与远端之通过JSON访问SQLServer 2005数据库