用Socket类实现HTTP协议客户端应用(二)

2014-11-23 20:08:37 · 作者: · 浏览: 40
otocol().toUpperCase().equals("HTTP") )
throw new ProtocolException("这不是HTTP协议");
this.target = target;
}catch(MalformedURLException m) {
throw new ProtocolException("协议格式错误");
}
}
/*
* 与Web服务器连接。若找不到Web服务器,InetAddress会引发UnknownHostException
* 异常。若Socket连接失败,会引发IOException异常。
*/
protected void openServer(String host,int port) throws
UnknownHostException,IOException {
header.clear();
responseMessage=""; responseCode=-1;
try {
if(client!=null) closeServer();
if(byteStream != null) {
byteStream.close(); byteStream=null;
}
InetAddress address = InetAddress.getByName(host);
client = new Socket(address,port==-1 80:port);
sender = new BufferedOutputStream(client.getOutputStream());
receiver = new BufferedInputStream(client.getInputStream());
}catch(UnknownHostException u) {
throw u;
}catch(IOException i) {
throw i;
}
}
/* 关闭与Web服务器的连接 */
protected void closeServer() throws IOException {
if(client==null) return;
try {
client.close(); sender.close(); receiver.close();
}catch(IOException i) {
throw i;
}
client=null; sender=null; receiver=null;
}
protected String getURLFormat(URL target) {
String spec = "http://"+target.getHost();
if(target.getPort()!=-1)
spec+=":"+target.getPort();
return spec+=target.getFile();
}

/* 向Web服务器传送数据 */
protected void sendMessage(String data) throws IOException{
sender.write(data.getBytes(),0,data.length());
sender.flush();
}
/* 接收来自Web服务器的数据 */
protected void receiveMessage() throws IOException{
byte data[] = new byte[1024];
int count=0;
int word=-1;
// 解析第一行
while( (word=receiver.read())!=-1 ) {
if(word== ||word== ) {
word=receiver.read();
if(word== ) word=receiver.read();
break;
}
if(count == data.length) data = addCapacity(data);
data[count++]=(byte)word;
}
String message = new String(data,0,count);
int mark = message.indexOf(32);
serverVersion = message.substring(0,mark);
while( mark
responseCode = Integer.parseInt(message.substring(mark+1,mark+=4));
responseMessage = message.substring(mark,message.length()).trim();

// 应答状态码和处理请读者添加
switch(responseCode) {
case 400:
throw new IOException("错误请求");
case 404:
throw new FileNotFoundException( getURLFormat(target) );
case 503:
throw new IOException("服务器不可用" );
}
if(word==-1) throw new ProtocolException("信息接收异常终止");
int symbol=-1;
count=0;
// 解析元信息
while( word!= && word!= && word>-1) {
if(word== ) word=32;
if(count==data.length) data = addCapacity(data);
data[count++] = (byte)word;
parseLine: {
while( (