Java Socket應答與HTTP服務器的關系
Java Socket應答一直伴隨著我們的編程生活,在不斷的發展中有很多知識需要我們學習。下面我們就先來看看有關Java Socket應答的代碼,有點長,但是看下去就會讓你豁然開朗。
HTTP/1.1表示這個HTTP服務器是1.1版,200是服務器對客戶請求的應答狀態碼,OK是對應答狀態碼的解釋,之后是這個文檔的元信息和文檔正文。(相關應答狀態碼和元信息的解釋請參閱Inetrnet標準草案:RFC2616)。
1.Http.java
2.import java.net.*;
3.import java.io.*;
4.import java.util.Properties;
5.import java.util.Enumeration;
6.public class Http {
7.protected Socket client;
8.protected BufferedOutputStream sender;
9.protected BufferedInputStream receiver;
10.protected ByteArrayInputStream byteStream;
11.protected URL target;
12.private int responseCode=-1;
13.private String responseMessage="";
14.private String serverVersion="";
15.private Properties header = new Properties();
16.public Http() { }
17.public Http(String url) {
18.GET(url) ;
19.}
20./* GET方法根據URL,會請求文件、數據庫查詢結果、程序運行結果等多種內容 */
21.public void GET(String url) {
22.try {
23.checkHTTP(url);
24.openServer(target.getHost(),target.getPort() );
25.String cmd = "GET "+ getURLFormat(target) +" HTTP/1.0\r\n"
26.+ getBaseHeads()+"\r\n";
27.sendMessage(cmd);
28.receiveMessage();
29.} catch(ProtocolException p) {
30.p.printStackTrace();
31.return;
32.} catch(UnknownHostException e) {
33.e.printStackTrace();
34.return;
35.} catch(IOException i) {
36.i.printStackTrace();
37.return;
38.}
39.}
40./*
41.* HEAD方法只請求URL的.元信息,不包括URL本身。若懷疑本機和服務器上的
42.* 文件相同,用這個方法檢查最快捷有效。
43.*/
44.public void HEAD(String url) {
45.try {
46.checkHTTP(url);
47.openServer(target.getHost(),target.getPort() );
48.String cmd = "HEAD "+getURLFormat(target)+" HTTP/1.0\r\n"
49.+getBaseHeads()+"\r\n";
50.sendMessage(cmd);
51.receiveMessage();
52.}catch(ProtocolException p) {
53.p.printStackTrace();
54.return;
55.}catch(UnknownHostException e) {
56.e.printStackTrace();
57.return;
58.}catch(IOException i) {
59.i.printStackTrace();
60.return;
61.}
62.}
63./*
64.* POST方法是向服務器傳送數據,以便服務器做出相應的處理。例如網頁上常用的
65.* 提交表格。
66.*/
67.public void POST(String url,String content) {
68.try {
69.checkHTTP(url);
70.openServer(target.getHost(),target.getPort() );
71.String cmd = "POST "+ getURLFormat(target) +"HTTP/1.0\r\n"+getBaseHeads();
72.cmd += "Content-type: application/x-www-form-urlencoded\r\n";
73.cmd += "Content-length: " + content.length() + "\r\n\r\n";
74.cmd += content+"\r\n";
75.sendMessage(cmd);
76.receiveMessage();
77.}catch(ProtocolException p) {
78.p.printStackTrace();
79.return;
80.}catch(UnknownHostException e) {
81.e.printStackTrace();
82.return;
83.}catch(IOException i) {
84.i.printStackTrace();
85.return;
86.}
87.}
88.protected void checkHTTP(String url) throws ProtocolException {
89.try {
90.URL target = new URL(url);
91.if(target==null || !target.getProtocol().toUpperCase().equals("HTTP") )
92.throw new ProtocolException("這不是HTTP協議");
93.this.target = target;
94.} catch(MalformedURLException m) {
95.throw new ProtocolException("協議格式錯誤");
96.}
97.}
98./*
99.* 與Web服務器連接。若找不到Web服務器,InetAddress會引發UnknownHostException
100.* 異常。若Socket連接失敗,會引發IOException異常。
101.*/
102.protected void openServer(String host,int port) throws
103.UnknownHostException,IOException {
104.header.clear();
105.responseMessage=""; responseCode=-1;
106.try {
107.if(client!=null) closeServer();
108.if(byteStream != null) {
109.byteStream.close(); byteStream=null;
110.}
111.InetAddress address = InetAddress.getByName(host);
112.client = new Socket(address,port==-1?80:port);
113.sender = new BufferedOutputStream(client.getOutputStream());
114.receiver = new BufferedInputStream(client.getInputStream());
115.}catch(UnknownHostException u) {
116.throw u;
117.}catch(IOException i) {
118.throw i;
119.}
120.}
121./* 關閉與Web服務器的連接 */
122.protected void closeServer() throws IOException {
123.if(client==null) return;
124.try {
125.client.close(); sender.close(); receiver.close();
126.} catch(IOException i) {
127.throw i;
128.}
129.client=null; sender=null; receiver=null;
130.}
131.protected String getURLFormat(URL target) {
132.String spec = "http://
133.+target.getHost();
134.if(target.getPort()!=-1)
135.spec+=":"+target.getPort();
136.return spec+=target.getFile();
137.}
138./* 向Web服務器傳送數據 */
139.protected void sendMessage(String data) throws IOException{
140.sender.write(data.getBytes(),0,data.length());
141.sender.flush();
142.}
143./* 接收來自Web服務器的數據 */
144.protected void receiveMessage() throws IOException{
145.byte data[] = new byte[1024];
146.int count=0;
147.int word=-1;
148.// 解析第一行
149.while( (word=receiver.read())!=-1 ) {
150.if(word=='\r'||word=='\n') {
151.word=receiver.read();
152.if(word=='\n') word=receiver.read();
153.break;
154.}
155.if(count == data.length) data = addCapacity(data);
156.data[count++]=(byte)word;
157.}
158.String message = new String(data,0,count);
159.int mark = message.indexOf(32);
160.serverVersion = message.substring(0,mark);
161.while( mark
162.responseCode = Integer.parseInt(message.substring(mark+1,mark+=4));
163.responseMessage = message.substring(mark,message.length()).trim();
164.// 應答狀態碼和處理請讀者添加
165.switch(responseCode) {
166.case 400:
167.throw new IOException("錯誤請求");
168.case 404:
169.throw new FileNotFoundException( getURLFormat(target) );
170.case 503:
171.throw new IOException("服務器不可用" );
172.}
173.if(word==-1) throw new ProtocolException("信息接收異常終止");
174.int symbol=-1;
175.count=0;
176.// 解析元信息
177.while( word!='\r' && word!='\n' && word>-1) {
178.if(word=='\t') word=32;
179.if(count==data.length) data = addCapacity(data);
180.data[count++] = (byte)word;
181.parseLine: {
182.while( (symbol=receiver.read()) >-1 ) {
183.switch(symbol) {
184.case '\t':
185.symbol=32; break;
186.case '\r':
187.case '\n':
188.word = receiver.read();
189.if( symbol=='\r' && word=='\n') {
190.word=receiver.read();
191.if(word=='\r') word=receiver.read();
192.}
193.if( word=='\r' || word=='\n' || word>32) break parseLine;
194.symbol=32; break;
195.}
196.if(count==data.length) data = addCapacity(data);
197.data[count++] = (byte)symbol;
198.}
199.word=-1;
200.}
201.message = new String(data,0,count);
202.mark = message.indexOf(':');
203.String key = null;
204.if(mark>0) key = message.substring(0,mark);
205.mark++;
206.while( mark
207.String value = message.substring(mark,message.length() );
208.header.put(key,value);
209.count=0;
210.}
211.// 獲得正文數據
212.while( (word=receiver.read())!=-1) {
213.if(count == data.length) data = addCapacity(data);
214.data[count++] = (byte)word;
215.}
216.if(count>0) byteStream = new ByteArrayInputStream(data,0,count);
217.data=null;
218.closeServer();
219.}
220.public String getResponseMessage() {
221.return responseMessage;
222.}
223.public int getResponseCode() {
224.return responseCode;
225.}
226.public String getServerVersion() {
227.return serverVersion;
228.}
229.public InputStream getInputStream() {
230.return byteStream;
231.}
232.public synchronized String getHeaderKey(int i) {
233.if(i>=header.size()) return null;
234.Enumeration enum = header.propertyNames();
235.String key = null;
236.for(int j=0; j<=i; j++)
237.key = (String)enum.nextElement();
238.return key;
239.}
240.public synchronized String getHeaderValue(int i) {
241.if(i>=header.size()) return null;
242.return header.getProperty(getHeaderKey(i));
243.}
244.public synchronized String getHeaderValue(String key) {
245.return header.getProperty(key);
246.}
247.protected String getBaseHeads() {
248.String inf = "User-Agent: myselfHttp/1.0\r\n"+
249."Accept: www/source; text/html; image/gif; */*\r\n";
250.return inf;
251.}
252.private byte[] addCapacity(byte rece[]){
253.byte temp[] = new byte[rece.length+1024];
254.System.arraycopy(rece,0,temp,0,rece.length);
255.return temp;
256.}
257.public static void main(String[] args) {
258.Http http=new Http();
259.//http.GET("http://192.168.1.5
260.);
261.int i;
262.for (i=0; i<50000; i++) {
263.http.GET("http://www.model-dl.com/modelinfo.asp?modelid=101 );
264.http.POST("http://www.model-dl.com/modelinfo.asp?modelid=101,"ratecontd=101&MM_insert=form1 ");
265.}
266.}
267.}
【Java Socket應答與HTTP服務器的關系】相關文章:
Java Web服務器(應用服務器)06-12
java實現web服務器的方法11-14
如何解決Java Socket通信技術收發線程互斥11-19
Java與Java web的區別11-10
常用的java應用服務器介紹05-27
PHP socket的配置11-23