📄 httpclient.java
字号:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.util.Properties;
import java.util.Enumeration;
public class HTTPClient{
protected Socket client;
protected BufferedOutputStream sender;
protected BufferedInputStream receiver;
protected ByteArrayInputStream byteStream;
protected URL target;
private int responseCode=-1;
private String responseMessage="";
private String serverVersion="";
private Properties header = new Properties();
public HTTPClient() { }
public HTTPClient(String url) {
GET(url) ;
}
/* GET????URL,????????????????????????? */
public void GET(String url) {
try {
checkHTTP(url);
openServer(target.getHost(),target.getPort() );
String cmd = "GET "+ getURLFormat(target)
+" HTTP/1.0\r\n"+ getBaseHeads()+"\r\n";
sendMessage(cmd);
receiveMessage();
}catch(ProtocolException p) {
p.printStackTrace();
return;
}catch(UnknownHostException e) {
e.printStackTrace();
return;
}catch(IOException i){
i.printStackTrace();
return;
}
}
/*
* HEAD?????URL????,???URL??????????????
* ????,?????????????
*/
public void HEAD(String url) {
try {
checkHTTP(url);
openServer(target.getHost(),target.getPort() );
String cmd = "HEAD "+getURLFormat(target)
+" HTTP/1.0\r\n"+getBaseHeads()+"\r\n";
sendMessage(cmd);
receiveMessage();
}catch(ProtocolException p) {
p.printStackTrace();
return;
}catch(UnknownHostException e) {
e.printStackTrace();
return;
}catch(IOException i){
i.printStackTrace();
return;
}
}
/*
* POST???????????,?????????????????????
* ?????
*/
public void POST(String url,String content) {
try {
checkHTTP(url);
openServer(target.getHost(),target.getPort() );
String cmd = "POST "+ getURLFormat(target)
+"HTTP/1.0\r\n"+getBaseHeads();
cmd += "Content-type: application/x-www-form-urlencoded\r\n";
cmd += "Content-length: " + content.length() + "\r\n\r\n";
cmd += content+"\r\n";
sendMessage(cmd);
receiveMessage();
}catch(ProtocolException p) {
p.printStackTrace();
return;
}catch(UnknownHostException e) {
e.printStackTrace();
return;
}catch(IOException i){
i.printStackTrace();
return;
}
}
protected void checkHTTP(String url) throws ProtocolException {
try {
URL target = new URL(url);
if(target==null || !target.getProtocol().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=='\r'||word=='\n') {
word=receiver.read();
if(word=='\n')
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<message.length() && message.charAt(mark+1)==32 )
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!='\r' && word!='\n' && word>-1) {
if(word=='\t')
word=32;
if(count==data.length)
data = addCapacity(data);
data[count++] = (byte)word;
parseLine: {
while( (symbol=receiver.read()) >-1 ) {
switch(symbol) {
case '\t':
symbol=32;
break;
case '\r':
case '\n':
word = receiver.read();
if( symbol=='\r' && word=='\n') {
word=receiver.read();
if(word=='\r')
word=receiver.read();
}
if( word=='\r' || word=='\n' || word>32)
break parseLine;
symbol=32;
break;
}
if(count==data.length)
data = addCapacity(data);
data[count++] = (byte)symbol;
}
word=-1;
}
message = new String(data,0,count);
mark = message.indexOf(':');
String key = null;
if(mark>0)
key = message.substring(0,mark);
mark++;
while( mark<message.length() && message.charAt(mark)<=32 )
mark++;
String value = message.substring(mark,message.length() );
header.put(key,value);
count=0;
}
// ??????
while( (word=receiver.read())!=-1) {
if(count == data.length)
data = addCapacity(data);
data[count++] = (byte)word;
}
if(count>0)
byteStream = new ByteArrayInputStream(data,0,count);
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>=header.size())
return null;
Enumeration enum = header.propertyNames();
String key = null;
for(int j=0; j<=i; j++)
key = (String)enum.nextElement();
return key;
}
public synchronized String getHeaderValue(int i) {
if(i>=header.size())
return null;
return header.getProperty(getHeaderKey(i));
}
public synchronized String getHeaderValue(String key) {
return header.getProperty(key);
}
protected String getBaseHeads() {
String inf = "User-Agent: myselfHttp/1.0\r\n"+
"Accept: www/source; text/html; image/gif; */*\r\n";
return inf;
}
private byte[] addCapacity(byte rece[]){
byte temp[] = new byte[rece.length+1024];
System.arraycopy(rece,0,temp,0,rece.length);
return temp;
}
public static void main(String args[]){
Frame f = new Frame("HTTPClient");
Label l = new Label("http://");
TextField tf = new TextField("127.0.0.1",20);
TextArea ta = new TextArea();
HTTPClient hc = new HTTPClient("http://127.0.0.1");
f.add(l);
f.add(tf);
f.pack();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -