JAVA實現HTTPserver端

來源:互聯網
上載者:User

標籤:

用java socket實現了一個簡單的httpserver, 能夠處理GET, POST,以及帶一個附件的multipart類型的POST。儘管中途遇到了非常多問題, 只是通過在論壇和幾個高手交流了一下,問題都攻克了。假設你認為程式有些地方看不明確,能夠參看這個文章:http://topic.csdn.net/u/20090625/22/59a5bfc8-a6b6-445d-9829-ea6d462a4fe6.html .

儘管解析http頭不是非常規範,本來應該用原始的位元組流, 我採用了一個折衷的方案,用DataInputStream.

本代碼的有用性==0,可是能夠協助非常好地瞭解http協議,然後其它的應用程式層協議大都如此。

假設你從來都沒有瞭解過http協議,建議先搜尋閱讀一下,或者你還能夠用以下的代碼來簡單的看一看究竟瀏覽器和server之間都相互發送了什麼資料。

MyHttpClient.java: 類比瀏覽器的行為, 向server發送get/post請求,然後列印出server返回的訊息。這樣就能夠查看當一個請求到來之後, server究竟都給瀏覽器發送了哪些訊息。

package socket;import java.io.*;import java.net.*;public class MyHttpClient {public static void main(String[] args) throws Exception{InetAddress inet = InetAddress.getByName("www.baidu.com");System.out.println(inet.getHostAddress());Socket socket = new Socket(inet.getHostAddress(),80);InputStream in = socket.getInputStream();OutputStream out = socket.getOutputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in));PrintWriter writer = new PrintWriter(out);writer.println("GET /home.html HTTP/1.1");//home.html是關於百度的頁面writer.println("Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");writer.println("Accept-Language: en-us,zh-cn;q=0.5");writer.println("Accept-Encoding: gzip, deflate");writer.println("Host: www.baidu.com");writer.println("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");writer.println("Connection: Keep-Alive");writer.println();writer.flush();String line = reader.readLine();while(line!=null){System.out.println(line);line = reader.readLine();}reader.close();writer.close();}}

MyServer.java: 類比server端接收瀏覽器的請求,然後把整個請求的報文列印出來。程式執行之後直接用瀏覽器測試。

package socket;import java.io.*;import java.net.*;public class MyServer {public static void main(String[] args) throws IOException{ServerSocket svrSocket = new ServerSocket(8080);while(true){Socket socket = svrSocket.accept();//足夠大的一個緩衝區byte[] buf = new byte[1024*1024];InputStream in = socket.getInputStream();int byteRead = in.read(buf, 0, 1024*1024);String dataString = new String(buf, 0, byteRead);System.out.println(dataString);in.close();socket.close();}}}

主程式MyHttpServer.

package socket;import java.io.*;import java.net.*;/** * MyHttpServer 實現一個簡單的HTTPserver端,能夠擷取使用者提交的內容 * 並給使用者一個response * 由於時間的關係,對http頭的處理顯得不規範 * 對於上傳附件,臨時僅僅能解析僅僅上傳一個附件並且附件位置在第一個的情況 * 轉載請註明來自http://blog.csdn.net/sunxing007 * **/public class MyHttpServer { //server根資料夾,post.html, upload.html都放在該位置 public static String WEB_ROOT = "c:/root"; //port private int port; //使用者請求的檔案的url private String requestPath; //mltipart/form-data方式提交post的分隔字元, private String boundary = null; //post提交請求的本文的長度 private int contentLength = 0; public MyHttpServer(String root, int port) { WEB_ROOT = root; this.port = port; requestPath = null; } //處理GET請求 private void doGet(DataInputStream reader, OutputStream out) throws Exception { if (new File(WEB_ROOT + this.requestPath).exists()) { //從server根資料夾下找到使用者請求的檔案並發送回瀏覽器 InputStream fileIn = new FileInputStream(WEB_ROOT + this.requestPath); byte[] buf = new byte[fileIn.available()]; fileIn.read(buf); out.write(buf); out.close(); fileIn.close(); reader.close(); System.out.println("request complete."); } } //處理post請求 private void doPost(DataInputStream reader, OutputStream out) throws Exception { String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); if ("".equals(line)) { break; } else if (line.indexOf("Content-Length") != -1) { this.contentLength = Integer.parseInt(line.substring(line.indexOf("Content-Length") + 16)); } //表明要上傳附件, 跳轉到doMultiPart方法。 else if(line.indexOf("multipart/form-data")!= -1){ //得multiltipart的分隔字元 this.boundary = line.substring(line.indexOf("boundary") + 9); this.doMultiPart(reader, out); return; } } //繼續讀取普通post(沒有附件)提交的資料 System.out.println("begin reading posted data......"); String dataLine = null; //使用者發送的post資料本文 byte[] buf = {}; int size = 0; if (this.contentLength != 0) { buf = new byte[this.contentLength]; while(size<this.contentLength){ int c = reader.read(); buf[size++] = (byte)c; } System.out.println("The data user posted: " + new String(buf, 0, size)); } //發送回瀏覽器的內容 String response = ""; response += "HTTP/1.1 200 OK/n"; response += "Server: Sunpache 1.0/n"; response += "Content-Type: text/html/n"; response += "Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT/n"; response += "Accept-ranges: bytes"; response += "/n"; String body = "<html><head><title>test server</title></head><body><p>post ok:</p>" + new String(buf, 0, size) + "</body></html>"; System.out.println(body); out.write(response.getBytes()); out.write(body.getBytes()); out.flush(); reader.close(); out.close(); System.out.println("request complete."); } //處理附件 private void doMultiPart(DataInputStream reader, OutputStream out) throws Exception { System.out.println("doMultiPart ......"); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); if ("".equals(line)) { break; } else if (line.indexOf("Content-Length") != -1) { this.contentLength = Integer.parseInt(line.substring(line.indexOf("Content-Length") + 16)); System.out.println("contentLength: " + this.contentLength); } else if (line.indexOf("boundary") != -1) { //擷取multipart分隔字元 this.boundary = line.substring(line.indexOf("boundary") + 9); } } System.out.println("begin get data......"); /*以下的凝視是一個瀏覽器發送帶附件的請求的全文,全部中文都是說明性的文字***** <HTTP頭部內容略> ............ Cache-Control: no-cache <這裡有一個空行,表明接下來的內容都是要提交的本文> -----------------------------7d925134501f6<這是multipart分隔字元> Content-Disposition: form-data; name="myfile"; filename="mywork.doc" Content-Type: text/plain <附件本文>........................................ ................................................. -----------------------------7d925134501f6<這是multipart分隔字元> Content-Disposition: form-data; name="myname"<其它欄位或附件> <這裡有一個空行> <其它欄位或附件的內容> -----------------------------7d925134501f6--<這是multipart分隔字元,最後一個分隔字元多兩個-> ****************************************************************/ /** * 上面的凝視是一個帶附件的multipart類型的POST的全文模型, * 要把附件去出來,就是要找到附件本文的起始位置和結束位置 * **/ if (this.contentLength != 0) { //把全部的提交的本文,包含附件和其它欄位都先讀到buf. byte[] buf = new byte[this.contentLength]; int totalRead = 0; int size = 0; while (totalRead < this.contentLength) { size = reader.read(buf, totalRead, this.contentLength - totalRead); totalRead += size; } //用buf構造一個字串,能夠用字串方便的計算出附件所在的位置 String dataString = new String(buf, 0, totalRead); System.out.println("the data user posted:/n" + dataString); int pos = dataString.indexOf(boundary); //下面略過4行就是第一個附件的位置 pos = dataString.indexOf("/n", pos) + 1; pos = dataString.indexOf("/n", pos) + 1; pos = dataString.indexOf("/n", pos) + 1; pos = dataString.indexOf("/n", pos) + 1; //附件開始位置 int start = dataString.substring(0, pos).getBytes().length; pos = dataString.indexOf(boundary, pos) - 4; //附件結束位置 int end = dataString.substring(0, pos).getBytes().length; //下面找出filename int fileNameBegin = dataString.indexOf("filename") + 10; int fileNameEnd = dataString.indexOf("/n", fileNameBegin); String fileName = dataString.substring(fileNameBegin, fileNameEnd); /** * 有時候上傳的檔案顯示完整的檔案名稱路徑,比方c:/my file/somedir/project.doc * 但有時候僅僅顯示檔案的名字,比方myphoto.jpg. * 所以須要做一個推斷。 */ if(fileName.lastIndexOf("//")!=-1){ fileName = fileName.substring(fileName.lastIndexOf("//") + 1); } fileName = fileName.substring(0, fileName.length()-2); OutputStream fileOut = new FileOutputStream("c://" + fileName); fileOut.write(buf, start, end-start); fileOut.close(); fileOut.close(); } String response = ""; response += "HTTP/1.1 200 OK/n"; response += "Server: Sunpache 1.0/n"; response += "Content-Type: text/html/n"; response += "Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT/n"; response += "Accept-ranges: bytes"; response += "/n"; out.write("<html><head><title>test server</title></head><body><p>Post is ok</p></body></html>".getBytes()); out.flush(); reader.close(); System.out.println("request complete."); } public void service() throws Exception { ServerSocket serverSocket = new ServerSocket(this.port); System.out.println("server is ok."); //開啟serverSocket等待使用者請求到來,然後依據請求的類別作處理 //在這裡我僅僅針對GET和POST作了處理 //當中POST具有解析單個附件的能力 while (true) { Socket socket = serverSocket.accept(); System.out.println("new request coming."); DataInputStream reader = new DataInputStream((socket.getInputStream())); String line = reader.readLine(); String method = line.substring(0, 4).trim(); OutputStream out = socket.getOutputStream(); this.requestPath = line.split(" ")[1]; System.out.println(method); if ("GET".equalsIgnoreCase(method)) { System.out.println("do get......"); this.doGet(reader, out); } else if ("POST".equalsIgnoreCase(method)) { System.out.println("do post......"); this.doPost(reader, out); } socket.close(); System.out.println("socket closed."); } } public static void main(String args[]) throws Exception { MyHttpServer server = new MyHttpServer("c:/root", 8080); server.service(); }}

測試檔案post.html, upload.html都放在上面程式定義的WEB_ROOT以下。

post.html:處理普通的post請求

<html> <head> <title>test my server</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <p>upload</p> 來自http://blog.csdn.net/sunxing007<br><form name="UploadForm" method="post" action="http://localhost:8080/"><input type="text" name="myname" /><br><select name="myage"> <option value="18">18</option> <option value="20">20</option> <option value="22">22</option></select><br><input type="submit"value="Sutmit"></form></body> </html>

upload.html:測試帶附件的post請求

<head><title>my page</title><style> table{ border-collapse: collapse; }</style></head><body>來自http://blog.csdn.net/sunxing007<br> <form action=‘http://localhost:8080/‘ method=‘post‘ enctype=‘multipart/form-data‘> file: <input type=‘file‘ name=‘myfile‘ /><br> <input type=‘submit‘ /> </form></body></html>

一切準備妥當,而且MyHttpServer執行之後, 在瀏覽器輸入http://localhost:8080/post.html和http://localhost:8080/upload.html就可以進行測試.

轉載請註明來自http://blog.csdn.net/sunxing007

JAVA實現HTTPserver端

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.