Android開發 httpclient Post方法實現從tomcat服務器(JSP)獲取listview信息

package com.example.httplistview;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {
	private Button refresh_bn;
	private MyHandler myhandler=new MyHandler();
	private refreshthread thread;
	private SimpleAdapter adapter;
	private ListView list;
	int flag=0;
	List<Map<String,Object>> listItems=new ArrayList<Map<String,Object>>();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		refresh_bn=(Button)findViewById(R.id.refresh);
		refresh_bn.setOnClickListener(new RefreshListener());
		list=(ListView)findViewById(R.id.mylist);		
		adapter=new SimpleAdapter(MainActivity.this, listItems, R.layout.list_item, new String[]{"ID","address","type","phone"},new int[]{R.id.number,R.id.address,R.id.type,R.id.phone}); 
		list.setAdapter(adapter);	
		
	}
	
public class RefreshListener implements OnClickListener{

	@Override
	public void onClick(View v) {
		thread=new refreshthread();
		listItems.clear();//不清除listitems的話,更新數據後之前的listview還會保留着
		thread.start();
	
	}
	
}

public class MyHandler extends Handler{

	@Override
	public void handleMessage(Message msg) {
		// TODO Auto-generated method stub
		super.handleMessage(msg);
		if(msg.what==0x123)
		{				      		
        		adapter.notifyDataSetChanged();      		
		}
	}
	
}

public class refreshthread extends Thread{

	@Override
	public void run() {
		super.run();
		System.out.println("1");
		Message msg=new Message();
		String httpUrl="http://192.168.0.103:8080/logintest/getListview.jsp";
		
		// 創建HttpPost連接對象
		HttpPost httpRequest=new HttpPost(httpUrl);
		System.out.println("1");
		// 使用NameValuePair來保存要傳遞的Post參數(鍵值對)
		List parameter=new ArrayList();	
       HttpEntity httpentity ;
        parameter.add(new BasicNameValuePair("name", "1"));
			
			try {
				httpentity = new UrlEncodedFormEntity(parameter, "gb2312");
				  // 請求httpRequset  
		        httpRequest.setEntity(httpentity);  
				 // 取得HttpClient  
		        HttpClient httpClient = new DefaultHttpClient();  
		         // 取得HttpResponse  
		        HttpResponse httpResponse;
				httpResponse = httpClient.execute(httpRequest);
				 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		        	 String strResult = EntityUtils.toString(httpResponse.getEntity());
		        	 InputStream input=httpRequest.getEntity().getContent();
		     //   	 System.out.println(input);
		       	 System.out.println(strResult);
		        	 //創建JSONObject
		        	 JSONArray jsonarray=new JSONArray(strResult);
		        	 
		        	 for (int i = 0; i < jsonarray.length(); i++) {
						// if(jsonarray.getJSONObject(i).getInt("id")==1){
		        		 	Map<String, Object> map = new HashMap<String, Object>();
							map.put("ID", jsonarray.getJSONObject(i).getString("ID"));
							map.put("address", jsonarray.getJSONObject(i).getString("address"));
							map.put("type",jsonarray.getJSONObject(i).getString("type"));
							map.put("phone",jsonarray.getJSONObject(i).getString("phone"));
							listItems.add(map);
						 }
					
					msg.what=0x123;
					myhandler.sendMessage(msg);
		        	
		        	 
		        }
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}         
	        // HttpStatus.SC_OK表示連接成功
			catch (JSONException e) {
				// TODO Auto-generated catch block
				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;
	}

}

tomcat上的JSP代碼:

<%@page import="net.sf.json.JSONArray"%>
<%@page import="java.sql.ResultSet"%>
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="net.sf.json.JSONObject" %>
<%@ page import="java.sql.ResultSetMetaData"  %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'getListview.jsp' starting page</title>
    
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">    
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
  
  <body>
  <% 
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//連接數據庫
   
    Connection con=DriverManager.getConnection("jdbc:odbc:userdata");
    Statement smt=con.createStatement();
    String sql="SELECT*FROM taskchoose";
    ResultSet rs=smt.executeQuery(sql);
    JSONArray jsonarray=new JSONArray();
    
    ResultSetMetaData metaData = rs.getMetaData();  
    int columnCount = metaData.getColumnCount();  //獲取列數
    // 遍歷ResultSet中的每條數據
 
    while(rs.next()){
     JSONObject jsonObj = new JSONObject();  
         for (int i = 1; i <= columnCount; i++) {  
      String columnName =metaData.getColumnLabel(i);  //獲取列名
      String value = rs.getString(columnName);  //獲取列值
      jsonObj.put(columnName, value);  //設置參數
     }   
  jsonarray.add(jsonObj);
    }
    response.getWriter().print(jsonarray.toString());
    
    %>
  </body>
</html>
 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章