服务器

位置:IT落伍者 >> 服务器 >> 浏览文章

Java Socket应答与HTTP服务器的瓜葛


发布日期:2020年08月03日
 
Java Socket应答与HTTP服务器的瓜葛

Java Socket应答一直伴随着我们的编程生活在不断的发展中有很多知识需要我们学习下面我们就先来看看有关Java <> Socket应答的代码有点长但是看下去就会让你豁然开朗

HTTP/表示这个HTTP服务器是是服务器对客户请求的应答状态码OK是对应答状态码的解释之后是这个文档的元信息和文档正文(相关应答状态码和元信息的解释请参阅Inetrnet标准草案:RFC)

Httpjava

import *;

import javaio*;

import javautilProperties;

import javautilEnumeration;

public class Http {

protected Socket client;

protected BufferedOutputStream sender;

protected BufferedInputStream receiver;

protected ByteArrayInputStream byteStream;

protected URL target;

private int responseCode=;

private String responseMessage=;

private String serverVersion=;

private Properties header = new Properties();

public Http() { }

public Http(String url) {

GET(url) ;

}

/* GET方法根据URL会请求文件数据库查询结果程序运行结果等多种内容 */

public void GET(String url) {

try {

checkHTTP(url);

openServer(targetgetHost()targetgetPort() );

String cmd = GET + getURLFormat(target) + HTTP/\r\n

+ getBaseHeads()+\r\n;

sendMessage(cmd);

receiveMessage();

} catch(ProtocolException p) {

pprintStackTrace();

return;

} catch(UnknownHostException e) {

eprintStackTrace();

return;

} catch(IOException i) {

iprintStackTrace();

return;

}

}

/*

* HEAD方法只请求URL的元信息不包括URL本身若怀疑本机和服务器上的

* 文件相同用这个方法检查最快捷有效

*/

public void HEAD(String url) {

try {

checkHTTP(url);

openServer(targetgetHost()targetgetPort() );

String cmd = HEAD +getURLFormat(target)+ HTTP/\r\n

+getBaseHeads()+\r\n;

sendMessage(cmd);

receiveMessage();

}catch(ProtocolException p) {

pprintStackTrace();

return;

}catch(UnknownHostException e) {

eprintStackTrace();

return;

}catch(IOException i) {

iprintStackTrace();

return;

}

}

/*

* POST方法是向服务器传送数据以便服务器做出相应的处理例如网页上常用的

* 提交表格

*/

public void POST(String urlString content) {

try {

checkHTTP(url);

openServer(targetgetHost()targetgetPort() );

String cmd = POST + getURLFormat(target) +HTTP/\r\n+getBaseHeads();

cmd += Contenttype: application/xwwwformurlencoded\r\n;

cmd += Contentlength: + contentlength() + \r\n\r\n;

cmd += content+\r\n;

sendMessage(cmd);

receiveMessage();

}catch(ProtocolException p) {

pprintStackTrace();

return;

}catch(UnknownHostException e) {

eprintStackTrace();

return;

}catch(IOException i) {

iprintStackTrace();

return;

}

}

protected void checkHTTP(String url) throws ProtocolException {

try {

URL target = new URL(url);

if(target==null || !targetgetProtocol()toUpperCase()equals(HTTP) )

throw new ProtocolException(这不是HTTP协议);

thistarget = target;

} catch(MalformedURLException m) {

throw new ProtocolException(协议格式错误);

}

}

/*

* 与Web服务器连接若找不到Web服务器InetAddress会引发UnknownHostException

* 异常若Socket连接失败会引发IOException异常

*/

protected void openServer(String hostint port) throws

UnknownHostExceptionIOException {

headerclear();

responseMessage=; responseCode=;

try {

if(client!=null) closeServer();

if(byteStream != null) {

byteStreamclose(); byteStream=null;

}

InetAddress address = InetAddressgetByName(host);

client = new Socket(addressport==?:port);

sender = new BufferedOutputStream(clientgetOutputStream());

receiver = new BufferedInputStream(clientgetInputStream());

}catch(UnknownHostException u) {

throw u;

}catch(IOException i) {

throw i;

}

}

/* 关闭与Web服务器的连接 */

protected void closeServer() throws IOException {

if(client==null) return;

try {

clientclose(); senderclose(); receiverclose();

} catch(IOException i) {

throw i;

}

client=null; sender=null; receiver=null;

}

protected String getURLFormat(URL target) {

String spec = //

+targetgetHost();

if(targetgetPort()!=)

spec+=:+targetgetPort();

return spec+=targetgetFile();

}

/* 向Web服务器传送数据 */

protected void sendMessage(String data) throws IOException{

senderwrite(datagetBytes()datalength());

senderflush();

}

/* 接收来自Web服务器的数据 */

protected void receiveMessage() throws IOException{

byte data[] = new byte[];

int count=;

int word=;

// 解析第一行

while( (word=receiverread())!= ) {

if(word==\r||word==\n) {

word=receiverread();

if(word==\n) word=receiverread();

break;

}

if(count == datalength) data = addCapacity(data);

data[count++]=(byte)word;

}

String message = new String(datacount);

int mark = messageindexOf();

serverVersion = messagesubstring(mark);

while( mark<messagelength() && messagecharAt(mark+)== ) mark++;

responseCode = IntegerparseInt(messagesubstring(mark+mark+=));

responseMessage = messagesubstring(markmessagelength())trim();

// 应答状态码和处理请读者添加

switch(responseCode) {

case :

throw new IOException(错误请求);

case :

throw new FileNotFoundException( getURLFormat(target) );

case :

throw new IOException(服务器不可用 );

}

if(word==) throw new ProtocolException(信息接收异常终止);

int symbol=;

unt=;

// 解析元信息

while( word!=\r && word!=\n && word>) {

if(word==\t) word=;

if(count==datalength) data = addCapacity(data);

data[count++] = (byte)word;

parseLine: {

while( (symbol=receiverread()) > ) {

switch(symbol) {

case \t:

symbol=; break;

case \r:

case \n:

word = receiverread();

if( symbol==\r && word==\n) {

word=receiverread();

if(word==\r) word=receiverread();

}

if( word==\r || word==\n || word>) break parseLine;

symbol=; break;

}

if(count==datalength) data = addCapacity(data);

data[count++] = (byte)symbol;

}

word=;

}

ssage = new String(datacount);

mark = messageindexOf(:);

String key = null;

if(mark>) key = messagesubstring(mark);

mark++;

while( mark<messagelength() && messagecharAt(mark)<= ) mark++;

String value = messagesubstring(markmessagelength() );

headerput(keyvalue);

unt=;

}

// 获得正文数据

while( (word=receiverread())!=) {

if(count == datalength) data = addCapacity(data);

data[count++] = (byte)word;

}

if(count>) byteStream = new ByteArrayInputStream(datacount);

data=null;

closeServer();

}

public String getResponseMessage() {

return responseMessage;

}

public int getResponseCode() {

return responseCode;

}

public String getServerVersion() {

return serverVersion;

}

public InputStream getInputStream() {

return byteStream;

}

public synchronized String getHeaderKey(int i) {

if(i>=headersize()) return null;

Enumeration enum = headerpropertyNames();

String key = null;

for(int j=; j<=i; j++)

key = (String)enumnextElement();

return key;

}

public synchronized String getHeaderValue(int i) {

if(i>=headersize()) return null;

return headergetProperty(getHeaderKey(i));

}

public synchronized String getHeaderValue(String key) {

return headergetProperty(key);

}

protected String getBaseHeads() {

String inf = UserAgent: myselfHttp/\r\n+

Accept: www/source; text/html; image/gif; */*\r\n;

return inf;

}

private byte[] addCapacity(byte rece[]){

byte temp[] = new byte[recelength+];

Systemarraycopy(recetemprecelength);

return temp;

}

public static void main(String[] args) {

Http http=new Http();

//httpGET(

);

int i;

for (i=; i<; i++) {

?modelid= );

?modelid=ratecontd=&MM_insert=form );

}

}

}

               

上一篇:Java实现简单web服务器

下一篇:JAVA实现支持视频点播WEB服务器