一、httpservice接口開發
httpservice是Java語言自帶的HTTP服務器,提供了豐富的HTTP服務端構建方法。它可以對底層的字節流封裝,對HTTP Header進行處理,提供訪問參數的各種方式等。
httpservice提供了HttpService接口,我們可以通過實現這個接口來開發HTTP服務端。在接口中,我們只需要實現handle方法,並在該方法中編寫處理HTTP請求的邏輯。
public interface HttpService {
void handle(
HttpRequest request,
HttpResponse response,
HttpContext context) throws HttpException, IOException;
}
其中,HttpRequest是封裝了HTTP頭和HTTP實體的類,HttpResponse封裝了響應頭和實體的類,HttpContext用來存儲HTTP上下文信息。
二、httpservice是什麼
httpservice是Java類庫中自帶的HTTP服務器,可以提供監聽HTTP請求,處理HTTP請求的功能。使用httpservice搭建HTTP服務端,既可以提供Web服務,也可以提供自定義的HTTP API接口。
httpservice使用簡單,輕量級,具有良好的可擴展性和性能優勢,可以處理同步和異步HTTP請求。
三、httpservice啟動項
在使用httpservice之前,需要新建一個HttpServer對象。HttpServer對象是httpservice中最為重要、最為基礎的啟動項。
HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080),0)
其中,create方法創建了一個默認的Server對象,同時綁定了一個監聽地址和端口號。第一個參數表示監聽端口號,第二個參數為可選參數,表示並發請求的隊列大小。
創建HttpServer對象後,需要註冊HttpHandler。HttpHandler是httpservice中對請求進行處理的關鍵。
httpServer.createContext("/",new MyHttpHandler())
上述代碼片段中,將MyHttpHandler對象註冊到監聽”/”路徑下,隨後便可以對該路徑下的請求進行處理。
四、httpservice實現接口調用
當接收到某個請求時,HttpHandler將根據請求的路徑查找具體的處理邏輯,並調用待實現的HttpService接口的實現類的handle方法。
下面是一個簡單的HttpService實現類,處理來自客戶端的請求並返回相應的Response。
public class MyHttpService implements HttpService {
@Override
public void handle(HttpRequest request, HttpResponse response,
HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD")) {
throw new MethodNotSupportedException(method + " method not supported");
}
//檢查URI是否請求了一個資源
String target = request.getRequestLine().getUri();
String queryString = "";
if(target.indexOf("?")>0){
queryString = target.substring(target.indexOf("?")+1);
target = target.substring(0,target.indexOf("?"));
}
//設置響應頭
response.setStatusCode(HttpStatus.SC_OK);
response.setEntity(new StringEntity(
"請求的資源:"
+target+"
"+queryString+"
", ContentType.create("text/html", "UTF-8")));
}
}
五、httpservice怎麼打開
httpservice的啟動方式比較靈活,可以在命令行或者腳本中啟動,也可以將它打包成一個可執行JAR文件。
下面是通過命令行方式啟動httpservice的方法:
C:\>java -cp "d:\myjar.jar" com.sun.net.httpserver.MyHttpHandler
其中,-cp參數表示類路徑,即jar文件路徑,com.sun.net.httpserver.MyHttpHandler是我們實現的HttpHandler類名。
六、httpservicerequest
HttpRequest對象就是來自客戶端的請求。通過HttpRequest對象,我們可以獲取請求的方法、路徑、參數等信息,也可以獲取請求頭或者實體內容。
下面是HttpRequest對象中常用的方法:
HttpRequest request = ... ;
request.getRequestLine().getMethod(); //獲取請求方法
request.getRequestLine().getUri(); //獲取請求路徑
request.getRequestLine().getProtocolVersion(); //獲取請求協議版本
request.getHeaders("Content-Type"); //獲取指定請求頭
request.getEntity(); //獲取請求實體
七、httpservice如何啟動
接下來,我們來看看通過Java代碼啟動httpservice的方式。方法如下:
public static void main(String[] args) throws IOException {
int port = 8080;
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/test", new MyHttpHandler());
server.createContext("/test1", new MyHttpHandler());
server.setExecutor(null); // creates a default executor
server.start();
System.out.println("Server is listening on port " + port);
}
當啟動httpservice後,它會監聽來自客戶端的請求。HttpHandler將解析客戶端的請求,並調用對應路徑下的HttpService實現類處理請求。
八、httpservice實例
下面的例子中,我們自定義了一個Hello World HttpService,它接收來自客戶端的請求,並以HTML格式返回“Hello World!”。
public class MyHttpService implements HttpService {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/hello", new MyHttpHandler());
server.start();
System.out.println("Server started.");
}
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
String query = request.getRequestLine().getUri().getQuery();
String name = query != null ? query : "World";
response.setEntity(new StringEntity(
"<html><body><h1>Hello, "+name+"!</h1></body></html>",
ContentType.create("text/html", "UTF-8")));
}
}
九、httpservice錯誤返回值選取
在httpservice中,當捕獲到異常後,一般會返回400、401、404、405等HTTP狀態碼。
下表列舉了httpservice中一些常用的HTTP錯誤碼以及相應的解釋:
| 錯誤碼 | 含義 |
|---|---|
| 400 | 請求參數錯誤 |
| 401 | 未經授權,拒絕訪問 |
| 404 | 請求的資源不存在 |
| 405 | 請求方法不允許 |
| 500 | 服務器內部錯誤 |
原創文章,作者:XALS,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/145525.html
微信掃一掃
支付寶掃一掃