Java Socket应答与HTTP服务器的关系

发布时间:2016-11-14 00:00:00 编辑:嘉辉 手机版

  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.}

本文已影响874
+1
0