⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 postoutputstream.java

📁 JAVA网络编程技术内幕一书的源代码
💻 JAVA
字号:
/* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN 188477749X * * http://nitric.com/jnp/ * * Copyright (c) 1997-1999 Merlin Hughes, Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */import java.io.*;
import java.net.*;
import java.util.*;

public class PostOutputStream extends FilterOutputStream {
  public PostOutputStream (URL url) {
    this (url, "application/x-www-form-urlencoded");
  }
  
  protected ByteArrayOutputStream byteArrayOut;
  protected URL url;
  protected String contentType;

  public PostOutputStream (URL url, String contentType) {
    super (new ByteArrayOutputStream ());
    byteArrayOut = (ByteArrayOutputStream) out;
    this.url = url;
    this.contentType = contentType;
  }

  public void writeString (String string) throws IOException {
    write (string.getBytes ("latin1"));
  }

  public void writeTag (String attr, String value) throws IOException {
    if (byteArrayOut.size () > 0)
      write ('&');
    writeString (encode (attr));
    write ('=');
    writeString (encode (value));
  }

  protected String encode (String string) {
    StringBuffer encoded = new StringBuffer ();
    for (int i = 0; i < string.length (); ++ i)
      encoded.append (encode ((char) (string.charAt (i) & 0xff)));
    return encoded.toString ();
  }

  protected String encode (char chr) {
    if (chr < 16) {
      return "%0" + Integer.toString (chr, 16);
    } else if ((chr < 32) || (chr > 127) || (" +&=%/~".indexOf (chr) >= 0)) {
      return "%" + Integer.toString (chr, 16);
    } else {
      return String.valueOf (chr);
    }
  }

  public void writeTags (Hashtable tags) throws IOException {
    Enumeration attrs = tags.keys ();
    while (attrs.hasMoreElements ()) {
      String attr = (String) attrs.nextElement ();
      writeTag (attr, (String) tags.get (attr));
    }
  }

  public InputStream post () throws IOException {
    int port = url.getPort ();
    if (port == -1)
      port = 80;
    Socket socket = new Socket (url.getHost (), port);
    try {
      OutputStream out = socket.getOutputStream ();
      Writer writer = new OutputStreamWriter (out, "latin1");
      writer.write ("POST " + url.getFile () + " HTTP/1.0\r\n");
      if (contentType != null)
        writer.write ("Content-type: " + contentType + "\r\n");
      writer.write ("Content-length: " + byteArrayOut.size () + "\r\n\n");
      writer.flush ();
      byteArrayOut.writeTo (out);
      byteArrayOut.reset ();
      return socket.getInputStream ();
    } catch (IOException ex) {
      try {
        socket.close ();
      } catch (IOException ignored) {
      }
      throw ex;
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -