編輯:關於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響應
源碼下載
Android仿新浪微博個人信息界面及其他效果
本教程為大家分享了Android微博個人信息界面設計代碼,供大家參考,具體內容如下根據用戶ID獲取用戶信息接口: http://open.weibo.com/wiki/2
Android Intent啟動別的應用實現方法
我們知道Intent的應用,可以啟動別一個Activity,那麼是否可以啟動別外的一個應用程序呢,答案是可以的。1、首先我們新建一個Android應用,名為Another
Android應用中繪制圓形頭像的方法解析
要畫這種圓形帶陰影的頭像,個人分解成三個圖層1,先畫頭像邊緣的漸變RadialGradient gradient = new RadialGradient(j/2,k/2
android顯示TextView文字的倒影效果實現代碼
今天記錄一下TextView的倒影效果,顯示一串文字,然後在文字的下方顯示出它的倒影,先上效果圖:最重要的就是View中getDrawingCache()方法,該方法可以