熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java Socket應答與HTTP服務器的瓜葛

2022-06-13   來源: Java核心技術 

  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 );

  }

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25854.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.