Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 網絡請求方法

Android 網絡請求方法

編輯:關於Android編程

在Android應用開發中,我們經常會與服務器交互,獲取或上傳數據,這就需要用到網絡請求,一般情況下是使用HTTP協議去發送和接收網絡數據,而HTTP又包括兩種通信方式,即:HttpUrlConnection和HttpClient。

 

代碼例子:https://git.oschina.net/ysx_xx/HttpText/tree/master

 

下面我簡單地介紹這兩種方式的使用:

 

首先,要進行網絡請求,我們要先給應用添加網絡權限,有兩種方式添加:

1. 打開AndroidManifest.xml文件,選擇permission,點擊Add:

\

 

選擇最後一個UsesPermission:

\

 

然後在右邊Name選項找到android.permission.INTERNET,保存

\

 

然後再選擇AndroidManifest.xml選項,就能看到

2.第二種方法其實就是直接在AndroidManifest中添加上面那句話,前提是你熟悉怎麼寫。

-------------------------------------------------------------------------------------------------------------------------------------------------------

 

好了,下面來講講那兩種請求方式的使用

1. HttpUrlConnection:

先new一個URL對象並傳入網絡地址,再調用openConnection()方法獲取HttpUrlConnection實例,然後設置HTTP請求的方法(GET/POST),接著設置連接超時、讀取超時、消息頭等,這個可以根據實際情況編寫,之後用getInputStream()方法獲取從服務器返回的輸入流,並讀取內容,最後調用disconnect()方法關閉。

代碼:

new Thread(new Runnable() {

			@Override
			public void run() {
				HttpURLConnection connection = null;
				try {
					URL url = new URL("http://www.baidu.com/");
					// 調用URL的openConnection()方法,得到HttpURLConnection的實例
					connection = (HttpURLConnection) url.openConnection();
					// 設置HTTP請求方法為GET,一般GET為從服務器獲取數據,POST為提交數據給服務器
					connection.setRequestMethod("GET");
					// 設置連接超時的毫秒數
					connection.setConnectTimeout(8000);
					// 設置讀取超時的毫秒數
					connection.setReadTimeout(8000);
					// 獲取服務器返回的輸入流
					InputStream in = connection.getInputStream();
					// 對獲取到的輸入流進行讀取
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(in));
					String response = "", line;
					while ((line = reader.readLine()) != null) {
						response += line;
					}
					//獲取成功,發送成功信息
					Message message = new Message();
					message.what = SUCCESS;
					message.obj = response;
					mHandler.sendMessage(message);
				} catch (Exception e) {
					//發送失敗信息
					Message message = new Message();
					message.what = FAILE;
					message.obj = "請求失敗";
					mHandler.sendMessage(message);
					e.printStackTrace();
				} finally {
					if (connection != null) {
						//如果connection為null,則關閉它
						connection.disconnect();
					}
				}
			}

		}).start();

運行效果如下:

\\\

 

 

以上是介紹GET方式,那如果要向服務器提交數據呢?

我們可以把請求方式改為POST,並提交參數

例如:

 

connection.setRequestMethod(“POST”);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(“username=小熊&password=123456”);

 

 

 

2. 下面來看看HttpClient的用法:

HttpClient是一個接口,我們要先創建一個DefaultHttpClient的實例,再創建一個HttpGet對象並傳入網絡地址,然後調用HttpClient的execute()方法發送GET請求,最後調用HttpResponse的getStatusLine()的getStatusCode()方法獲取服務器返回的狀態碼,如果為200則說明成功

代碼:

 

new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					//因為HttpClient是一個接口,所以用DefaultHttpClient()方法創建一個實例
					HttpClient httpClient = new DefaultHttpClient();
					//創建HttpGet對象並傳入網絡地址,並調用HttpClient的execute方法發送GET請求
					HttpGet httpGet = new HttpGet("http://www.baidu.com");
					HttpResponse httpResponse = httpClient.execute(httpGet);
					//先取出服務器返回的狀態碼,如果是200則說明請求響應成功,這裡可以自行判斷獲得的狀態碼
					//是什麼來判斷是否成功或是什麼失敗
					if(httpResponse.getStatusLine().getStatusCode() == 200){
						//請求響應成功,調用getEntity()方法獲取HttpEntity實例並轉換成字符串
						HttpEntity entity = httpResponse.getEntity();
						String response = EntityUtils.toString(entity, "utf-8");

						//獲取成功,發送成功信息
						Message message = new Message();
						message.what = SUCCESS;
						message.obj = response;
						mHandler.sendMessage(message);
					}
				} catch (Exception e) {
					//發送失敗信息
					Message message = new Message();
					message.what = FAILE;
					message.obj = "請求失敗";
					mHandler.sendMessage(message);
					e.printStackTrace();
				}
			}

		}).start();

 

運行效果跟HttpURLConnection一樣,這裡就不多發一遍了。下面是HttpClient的POST方式:

關鍵代碼:

HttpPost httpPost = new HttpPost("http://www.baidu.com");
					List params = new ArrayList();
					params.add(new BasicNameValuePair("username", "小熊"));
					params.add(new BasicNameValuePair("password", "123456"));
					UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
					httpPost.setEntity(entity);
					httpClient.execute(httpPost);

完整代碼:

HttpURLConnectionText.java:

 

public class HttpURLConnectionText extends Activity implements OnClickListener {

	private final static int SUCCESS = 1;
	private final static int FAILE = 0;
	private TextView result;
	private Button send;
	private LoadingDialog loadingDialog;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initData();
	}

	private void initData() {
		mContext = this;
		result = (TextView) findViewById(R.id.result);
		send = (Button) findViewById(R.id.send);
		send.setOnClickListener(this);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			String response;
			if(loadingDialog != null && loadingDialog.isShowing()){
				loadingDialog.dismiss();
			}
			switch (msg.what) {
			case SUCCESS:
				response = msg.obj.toString();
				result.setText(response);
				break;
			case FAILE:
				response = msg.obj.toString();
				result.setText(response);
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send:
			loadingDialog = new LoadingDialog(mContext);
			loadingDialog.setCancel(false);
			loadingDialog.show();
			startSend();
			break;
		}
	}

	private void startSend() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				HttpURLConnection connection = null;
				try {
					URL url = new URL("http://www.baidu.com/");
					// 調用URL的openConnection()方法,得到HttpURLConnection的實例
					connection = (HttpURLConnection) url.openConnection();
					// 設置HTTP請求方法為GET,一般GET為從服務器獲取數據,POST為提交數據給服務器
					connection.setRequestMethod("GET");
					// 設置連接超時的毫秒數
					connection.setConnectTimeout(8000);
					// 設置讀取超時的毫秒數
					connection.setReadTimeout(8000);
					// 獲取服務器返回的輸入流
					InputStream in = connection.getInputStream();
					// 對獲取到的輸入流進行讀取
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(in));
					String response = "", line;
					while ((line = reader.readLine()) != null) {
						response += line;
					}
					//獲取成功,發送成功信息
					Message message = new Message();
					message.what = SUCCESS;
					message.obj = response;
					mHandler.sendMessage(message);
				} catch (Exception e) {
					//發送失敗信息
					Message message = new Message();
					message.what = FAILE;
					message.obj = "請求失敗";
					mHandler.sendMessage(message);
					e.printStackTrace();
				} finally {
					if (connection != null) {
						//如果connection為null,則關閉它
						connection.disconnect();
					}
				}
			}

		}).start();
	}

}

 

HttpClientText.java:

public class HttpClientText extends Activity implements OnClickListener {

	private final static int SUCCESS = 1;
	private final static int FAILE = 0;
	private TextView result;
	private Button send;
	private LoadingDialog loadingDialog;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initData();
	}

	private void initData() {
		mContext = this;
		result = (TextView) findViewById(R.id.result);
		send = (Button) findViewById(R.id.send);
		send.setOnClickListener(this);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			String response;
			if(loadingDialog != null && loadingDialog.isShowing()){
				loadingDialog.dismiss();
			}
			switch (msg.what) {
			case SUCCESS:
				response = msg.obj.toString();
				result.setText(response);
				break;
			case FAILE:
				response = msg.obj.toString();
				result.setText(response);
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send:
			loadingDialog = new LoadingDialog(mContext);
			loadingDialog.setCancel(false);
			loadingDialog.show();
			startSend();
			break;
		}
	}

	private void startSend() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					//因為HttpClient是一個接口,所以用DefaultHttpClient()方法創建一個實例
					HttpClient httpClient = new DefaultHttpClient();
					//創建HttpGet對象並傳入網絡地址,並調用HttpClient的execute方法發送GET請求
					HttpGet httpGet = new HttpGet("http://www.baidu.com");
					HttpResponse httpResponse = httpClient.execute(httpGet);
					//先取出服務器返回的狀態碼,如果是200則說明請求響應成功,這裡可以自行判斷獲得的狀態碼
					//是什麼來判斷是否成功或是什麼失敗
					if(httpResponse.getStatusLine().getStatusCode() == 200){
						//請求響應成功,調用getEntity()方法獲取HttpEntity實例並轉換成字符串
						HttpEntity entity = httpResponse.getEntity();
						String response = EntityUtils.toString(entity, "utf-8");

						//獲取成功,發送成功信息
						Message message = new Message();
						message.what = SUCCESS;
						message.obj = response;
						mHandler.sendMessage(message);
					}
				} catch (Exception e) {
					//發送失敗信息
					Message message = new Message();
					message.what = FAILE;
					message.obj = "請求失敗";
					mHandler.sendMessage(message);
					e.printStackTrace();
				}
			}

		}).start();
	}

}
 



 

 

 

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