第十七天 樂在其中-Android與遠端之通過JSON訪問SQLServer 2005資料庫
阿新 • • 發佈:2019-02-14
5月10日,中雨。“黑雲翻墨未遮山, 白雨跳珠亂入船。卷地風來忽吹散, 望湖樓下水如天。”
在SQLServer 2005建立資料庫librarydb,供測試使用. 建立方法見第十一天部落格。
1、伺服器端
(1)工程檢視
(2)AndroidServlet.java
(3)執行http://192.168.23.1:8080/ServletForJsonSqlserver2005/AndroidServletpackage 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); } }
注意:IP:192.168.23.1:8080,是WIFI共享精靈設定的虛擬的無線網絡卡的IP,IP自然由虛擬的無線路由分配,使用手機連線,會自動給手機分配同一網段的IP:如:192.168.23.2。
2、手機端程式碼
(1)工程檢視
(2)MainActivity.java
(3)main.xmlpackage 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; } }
(4)strings.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>
<?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、安卓模擬器執行結果6、手機執行結果-手機截圖