Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android版Web服務器實現(三)HTTP響應

Android版Web服務器實現(三)HTTP響應

編輯:關於Android編程

《Android版Web服務器實現(二)使用服務來監聽HTTP請求》一文實現了HTTP請求的監聽,那麼我們要如何作出響應呢?在響應時,有幾種情況。

1、請求的方法不支持。比如服務端僅支持了GET/POST方法,而請求卻有DELETE等,此時回復501。

2、請求的資源不存在。在服務端不存在該資源文件,將回復404頁面。

3、請求的類型不支持。服務端可能存在該資源,但是該資源的類型沒有支持,將回復404.7。

4、請求正常。服務端將相應的資源回復給客戶端。

5、其他情況。

下面是依據這些情況的代碼實現。

SessionThread.java

package com.sparkle.webservice;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import android.util.Log;

public class SessionThread extends Thread {

	private Socket _clientSocket = null;
	private final int BUFFER_MAX = 8192;
	private DataHandle _dataHandle = null;
	private MyLog _myLog = new MyLog(getClass().getName());

	public SessionThread(Socket clientSocket) {
		this._clientSocket = clientSocket;
	}

	public void closeSocket() {
		if (_clientSocket == null) {
			return;
		}
		try {
			_clientSocket.close();
		} catch (IOException e) {
			_myLog.e(e.getMessage());
		}
	}

	public void run() {
		try {

			InputStream socketInput = _clientSocket.getInputStream();
			byte[] buffer = new byte[BUFFER_MAX];
			socketInput.read(buffer);
			_dataHandle = new DataHandle(buffer);
			byte[] content = _dataHandle.fetchContent();

			sendResponse(_clientSocket, content);

		} catch (Exception e) {
			_myLog.l(Log.DEBUG, "Exception in TcpListener");
		}
	}

	private void sendResponse(Socket clientSocket, byte[] content) {
		try {
			OutputStream socketOut = clientSocket.getOutputStream();

			byte[] header = _dataHandle.fetchHeader(content.length);

			socketOut.write(header);
			socketOut.write(content);

			socketOut.close();
			clientSocket.close();
		} catch (Exception e) {
		}
	}

}
注:

1、在收到請求後,新建一個SessionThread來處理請求(在上一篇中有說到)。

2、SessionThread建立後,在run中新建DataHandle來處理數據,具體請參看後文代碼。

3、在sendResponse來回應請求。

4、在響應時,先發送header,再發送content來響應

DataHandle.java

package com.sparkle.webservice;

import java.io.UnsupportedEncodingException;

import com.sparkle.io.FileSp;

import android.annotation.SuppressLint;
import android.util.Log;

public class DataHandle {

	private String _receiveInfo = "";
	private HttpHeader _httpHeader = null;
	private String _encoding = "utf-8";
	private String _serverName = "Simple Web Server";
	private String _responseCode = "200 OK";
	private String _contentType = "text/html";

	public DataHandle(byte[] recieveData) {
		try {
			this._receiveInfo = new String(recieveData, _encoding);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		_httpHeader = new HttpHeader(_receiveInfo);
	}

	public byte[] fetchContent() {
		byte[] backData = null;
		if (!isSupportMethod()) {
			backData = fetchNotSupportMethodBack();
			return backData;
		}

		String filePath = fetchFilePath();
		boolean hasFile=FileSp.isExist(filePath);
		Log.e("FilePath", filePath+"   "+hasFile);
		if (!hasFile) {
			backData = fetchNotFoundBack();
			return backData;
		}

		if (!isSupportExtension()) {
			backData = fetchNotSupportFileBack();
			return backData;
		}

		backData = fetchBackFromFile(filePath);
		return backData;
	}

	public byte[] fetchHeader(int contentLength) {
		byte[] header = null;
		try {
			header = ("HTTP/1.1 " + _responseCode + "\r\n" 
					+ "Server: "+ _serverName + "\r\n" 
					+ "Content-Length: " + contentLength+ "\r\n"
					+ "Connection: close\r\n" 
					+ "Content-Type: "+ _contentType + ";charset="+_encoding+"\r\n\r\n").getBytes(_encoding);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return header;
	}

	@SuppressLint("DefaultLocale")
	private boolean isSupportMethod() {
		String method = _httpHeader.getMethod();
		if (method == null || method.length() <= 0) {
			return false;
		}
		method = method.toUpperCase();
		if (method.equals("GET") || method.equals("POST")) {
			return true;
		}

		return false;
	}

	private boolean isSupportExtension() {
		String contentType = _httpHeader.getContentType();
		if (contentType == null || contentType.length() <= 0) {
			return false;
		}
		_contentType=contentType;
		return true;
	}

	private byte[] fetchNotSupportMethodBack() {
		byte[] backData = null;
		String notImplementMethod = "

" + _serverName + "

501 - Method Not Implemented"; try { backData = notImplementMethod.getBytes(_encoding); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return backData; } private byte[] fetchNotSupportFileBack() { byte[] backData = null; String notImplementMethod = "

" + _serverName + "

404.7 Not Found(Type Not Support)"; try { backData = notImplementMethod.getBytes(_encoding); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return backData; } private byte[] fetchBackFromFile(String filePath) { byte[] content = null; content = FileSp.read(filePath); return content; } private String fetchFilePath() { String root = Defaults.getRoot(); String fileName = _httpHeader.getFileName(); String filePath = ""; if (fileName.startsWith("/") || fileName.startsWith("\\")) { filePath = root + fileName.substring(1); } else { filePath = root + fileName; } return filePath; } private byte[] fetchNotFoundBack() { byte[] notFoundData = null; String notFoundStr = "

" + _serverName + "

404 - Not Found"; try { notFoundData = notFoundStr.getBytes(_encoding); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return notFoundData; } }
注:

1、isSupportMethod判斷是否是支持的方法,如果不支持,從fetchNotSupportMethodBack獲取數據進行響應。

2、判斷請求的資源是否存在,如果不存在,從fetchNotFoundBack獲取數據進行響應。

3、isSupportExtension判斷是否是支持的數據類型,如果不支持,從fetchNotSupportFileBack獲取數據進行響應。

4、請求方法支持、請求資源存在,且請求類型支持,將從fetchBackFromFile獲取數據進行響應。

在對HTTP作出相應的響應之後,現在就剩下如果在界面中實現相應的控制了,具體請看下一篇。

轉載請注明出處:Android版Web服務器實現(三)HTTP響應

源碼下載

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