Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android客戶端使用HttpClient發起web數據訪問

Android客戶端使用HttpClient發起web數據訪問

編輯:關於Android編程

HttpClient與服務器數據交互方式:HttpPost和HttpGet 分別對應Post和Get提交。因為要做Android客戶端的緣故,所以就必須實現客戶端與服務器實現數據交互,以保證數據鏈條的通暢,實現數據閉環。由於之前對Android客戶端訪問web數據沒有設置權限,所以可以很好的訪問系統資源,但是如果是開發應用這種方式就存在極大的安全隱患,一個Host或Get提交過去數據就獲取到了,web端系統完全就是裸奔。所以web端權限管理很有必要,也就不用過於擔心Android客戶端帶來的安全隱患。Android新手學習一般都會遇到問題,前兩天就遇到web端設置了權限而Android客戶端發起訪問獲取不到數據的問題。

 

1.HttpPost與HttpGet實現用戶登錄和列表展現

編寫一個測試Activity,MainActivity.

 

package com.boonya.httpclienttest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;
import com.boonya.httpclienttest.utils.HtttpClientUtil;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity
{

	private static final String TAG = MainActivity;

	private List> videos = null;

	private HashMap video = null;

	private ListView listView = null;
	
	private static String loginurl = http://192.168.1.147:8090/wtms/androidservice/login;
	
	private static String getdataurl = http://192.168.1.147:8090/wtms/androidservice/videos.avd;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		listView = (ListView) findViewById(R.id.videos);
		
		postMethod();

		getMethod();
	}

	/**
	 * HttpGet獲取服務器數據顯示
	 * 
	 * @param url
	 */
	protected void getMethod()
	{
	    HttpGet request = new HttpGet(getdataurl);  
	    //request.setHeader(Cookie, HtttpClientUtil.getCookie());//設置cookie 
		try
		{
			//設置請求參數項  
            //request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
            HttpClient client = HtttpClientUtil.getInstance();  
            //執行請求返回相應  
            HttpResponse response = client.execute(request);
			// 判斷請求是否成功
			if (response.getStatusLine().getStatusCode() == 200)
			{ // 200表示請求成功

				StringBuilder builder = new StringBuilder();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

				String s = null;
				while ((s = bufferedReader.readLine()) != null)
				{
					builder.append(s);
				}

				// String out = EntityUtils.toString(entity, UTF-8);
				String msg = builder.toString();
				
				Log.d(log, >>>>執行 方法 getMethod()獲取到范圍值:+msg);

				JSONArray jsonArray = new JSONArray(msg);

				videos = new ArrayList>();
				for (int i = 0; i < jsonArray.length(); i++)
				{
					JSONObject jsonObject = (JSONObject) jsonArray.get(i);
					int id = jsonObject.getInt(id);
					String name = jsonObject.getString(name);
					int timelength = jsonObject.getInt(time);

					video = new HashMap();
					video.put(id, id);
					video.put(name, name);
					video.put(timelength, 時長為: + timelength);

					videos.add(video);
				}

				SimpleAdapter adapter = new SimpleAdapter(this, videos, R.layout.item, new String[]
				{ name, timelength }, new int[]
				{ R.id.title, R.id.timelength });
				listView.setAdapter(adapter);

			}
		} catch (Exception e)
		{
			e.printStackTrace();
			Log.e(TAG, e.toString());
			Toast.makeText(MainActivity.this, 獲取數據失敗, Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * HttpPost提交數據
	 */
	@SuppressWarnings(
	{ unchecked, rawtypes })
	protected void postMethod()
	{

		try
		{
			// 使用ApacheHttp客戶端進行連接(重要方法)
			HttpClient client = HtttpClientUtil.getInstance();

			// 如果是Get提交則創建HttpGet對象,否則創建HttpPost對象
			// POST提交的方式
			HttpPost request = new HttpPost(loginurl);
			// 如果是Post提交可以將參數封裝到集合中傳遞
			List params = new ArrayList();
			params.add(new BasicNameValuePair(username, test));
			params.add(new BasicNameValuePair(password, test));
			// UrlEncodedFormEntity用於將集合轉換為Entity對象
			request.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
			try
			{
				// 獲取相應消息
				HttpResponse response = client.execute(request);
				StringBuilder builder = new StringBuilder(); 
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
                // 操作cookie
               /* List cookies = ((AbstractHttpClient) client).getCookieStore().getCookies();
                if(cookies!=null&&cookies.size()>0)
                {
                	for (int i = 0; i < cookies.size(); i++)
					{
						HtttpClientUtil.setCookie(cookies.get(i).getValue());
					}
                }*/
                String s =null;
                while((s = bufferedReader.readLine())!=null){
                	builder.append(s); 
                }
                
                String string=builder.toString();
            	Log.d(log, >>>>執行 方法 postMethod()獲取到范圍值:+string);
            	
			} catch (ClientProtocolException e)
			{
				e.printStackTrace();
			} catch (IOException e)
			{
				e.printStackTrace();
			}

		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}

	}
	
}

 

2.實現客戶端與服務器cookie共享

這裡采用單例模式實現HttpClient對象在Android客戶端的唯一性,用戶在登錄系統後,這個對象會記錄用戶的Cookie,一旦建立客戶端與服務器的訪問認證,以後就可以任意發送HTTP請求到服務器請求或操作資源了。

 

package com.boonya.httpclienttest.utils;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

public class HtttpClientUtil
{
	/** 設置請求超時10秒鐘 */
	private static final int REQUEST_TIMEOUT = 10 * 1000;
	
	/** 設置等待數據超時時間10秒鐘 */
	private static final int SO_TIMEOUT = 10 * 1000;

	private static HttpClient instance;
	
	/**  記住cookie字符串*/
	private static String cookie;

	/**
	 * 自定義方法:初始化HttpClient,並設置超時
	 * 
	 * @return 返回:HttpClient 對象
	 */
	private HtttpClientUtil()
	{

	}
	
	public static String getCookie()
	{
		return cookie;
	}



	public static void setCookie(String cookie)
	{
		HtttpClientUtil.cookie = cookie;
	}



	public static HttpClient getInstance()
	{
		if (instance == null)
		{
			BasicHttpParams httpParams = new BasicHttpParams();

			HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);

			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);

			instance = new DefaultHttpClient(httpParams);
		}
		return instance;
	}

}
上面cookie字段並非必須的,如果HttpClient不是單例的,那麼用戶需要在靜態變量來記住登錄後的cookie。

 

優化HttpClientUtil的cookie獲取方法:

 

package com.boonya.httpclienttest.utils;

import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

public class HtttpClientUtil
{
	/** 設置請求超時10秒鐘 */
	private static final int REQUEST_TIMEOUT = 10 * 1000;

	/** 設置等待數據超時時間10秒鐘 */
	private static final int SO_TIMEOUT = 10 * 1000;

	private static HttpClient instance;

	/** 記住cookie字符串 */
	private static String cookie = null;

	/**
	 * 自定義方法:初始化HttpClient,並設置超時
	 * 
	 * @return 返回:HttpClient 對象
	 */
	private HtttpClientUtil()
	{

	}

	public static String getCookie()
	{
		// 確保實例存在
		HtttpClientUtil.getInstance();
		// 獲取cookie
		List cookies = ((AbstractHttpClient) instance).getCookieStore().getCookies();
		if (cookies != null && cookies.size() > 0)
		{
			for (int i = 0; i < cookies.size(); i++)
			{
				cookie = cookies.get(i).getValue();
			}
		}
		return cookie;
	}

	public static HttpClient getInstance()
	{
		if (instance == null)
		{
			BasicHttpParams httpParams = new BasicHttpParams();

			HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);

			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);

			instance = new DefaultHttpClient(httpParams);
		}
		return instance;
	}

}


 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved