httprequest.java

来自「Hecl编程语言是一个高层次的脚本语言的Java实现。其用意是要小」· Java 代码 · 共 686 行 · 第 1/2 页

JAVA
686
字号
	    return "ok";	  default:	    return "unknown";	}    }        public static byte[] IRIencode(String str) {	int strlen = str.length();	int utflen = 0; 	char[] charr = new char[strlen];	int c, count = 0;		str.getChars(0, strlen, charr, 0); 	for (int i = 0; i < strlen; i++) {	    c = charr[i];	    if ((c >= 0x0001) && (c <= 0x007F)) {		utflen++;	    } else if (c > 0x07FF) {		utflen += 3;	    } else {		utflen += 2;	    }	}	byte[] bytearr = new byte[utflen];	for (int i = 0; i < strlen; i++) {	    c = charr[i];	    if ((c >= 0x0001) && (c <= 0x007F)) {		bytearr[count++] = (byte)c;	    } else if (c > 0x07FF) {		bytearr[count++] = (byte)(0xE0 | ((c >> 12) & 0x0F));		bytearr[count++] = (byte)(0x80 | ((c >>  6) & 0x3F));		bytearr[count++] = (byte)(0x80 | ((c >>  0) & 0x3F));	    } else {		bytearr[count++] = (byte)(0xC0 | ((c >>  6) & 0x1F));		bytearr[count++] = (byte)(0x80 | ((c >>  0) & 0x3F));	    }	}	return bytearr;    }    public static String urlencode(byte[] s,int start, int n) {	StringBuffer b = new StringBuffer();	for(int i = start; n>0; ++i, --n) {	    b.append(urlencodemap[s[i] & 0xff]);	}	return b.toString();    }    public static String urlencode(byte[] s) {	return urlencode(s,0,s.length);    }    public static String urlencode(String[] elems) {	if(elems == null || elems.length == 0)	    return null;		StringBuffer b = new StringBuffer();	if(elems != null) {	    for(int i = 0; i < elems.length; ++i) {		if(i > 0) {		    b.append((i % 2) != 0 ? '=' : '&');		}		b.append(urlencode(IRIencode(elems[i])));	    }	}	return b.toString();    }    private boolean isISOCharset(String charset) {	String lower = charset.toLowerCase();		for(int i=0; i<ISOALIASES.length; ++i) {	    if(lower.equals(ISOALIASES[i]))		return true;	}	return false;    }        private String urlstr = null;    private byte[] inData = null;    private String body = "";    private String qdata = null;    private QueryParam[] qparams = null;    private String requestMethod =//#ifdef j2me    HttpConnection.GET//#else    GET//#endif    ;    private int rc = -1;    private short status = SETUP;    Exception error = null;    private Hashtable requestFields = new Hashtable();    private Hashtable responseFields = new Hashtable();    private static String[] urlencodemap = new String[256];    private static String validUrlChars =    "-_.!~*'()\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";    private static final char[] hexchars = (new String("0123456789ABCDEF")).toCharArray();    public static boolean DEBUGURL = false;    public static boolean DEBUGRC = false;    public static boolean DEBUGBODY = false;    public static String DEFCHARSET = "ISO8859-1";    public static final String CONTENTTYPE = "content-type";    public static final String CONTENTENCODING = "content-encoding";    static private final String ISOALIASES[]= {	"iso-8859-1","iso8859-1","iso8859_1","iso_8859_1","iso-8859_1","iso_8859-1"    };        static {	char[] cbuf = new char[3];	for(int i = 0; i < 256; i++) {	    char ch = (char)i;	    int idx = validUrlChars.indexOf(ch);	    if(idx >= 0) {		urlencodemap[i] = validUrlChars.substring(idx, idx + 1);	    } else {		// !!! Do not use 		// urlencodemap[i] = "%" + Integer.toHexString(i);		// since it does not print leading 0s		cbuf[0] = '%';		cbuf[1] = hexchars[(i&0xf0)>>4];		cbuf[2] = hexchars[i&0x0f];		urlencodemap[i] = new String(cbuf);	    }	}	urlencodemap[' '] = "+";	//urlencodemap['\n'] = "%0D%0A";    }}class MyHttpConn {    MyHttpConn(String url) throws IOException {	is = null;	os = null;	conn = null;//#if javaversion >= 1.5 || cldc > 1.0	secure = url.toLowerCase().startsWith("https");//#endif	if(HttpRequest.DEBUGURL)	    System.err.println("url="+url);//#ifdef j2me//#if cldc > 1.0	conn = secure ?	    (HttpsConnection)	    Connector.open(url/*,Connector.READ_WRITE, true*/) :	    (HttpConnection)	    Connector.open(url/*,Connector.READ_WRITE, true*/);//#else	conn = (HttpConnection)	    Connector.open(url/*,Connector.READ_WRITE, true*/);//#endif//#else	URL myurl = new URL(url);	conn = secure ? (HttpsURLConnection) myurl.openConnection() :	    (HttpURLConnection)myurl.openConnection();//#endif    }    void connect(String rm, Hashtable rfields,			String qdata,QueryParam[] qparams)	throws IOException {	conn.setRequestMethod(rm);	// Set the request fields.	Enumeration e = rfields.keys();	//System.err.println("--- REQUEST -------------------------------------");	while (e.hasMoreElements()) {	    String key = (String)e.nextElement();	    //System.err.println("key: " + key + ", value: " + (String)rfields.get(key));	    conn.setRequestProperty(key, (String)rfields.get(key));	}//#ifndef j2me	if (qdata != null || qparams != null) {	    conn.setDoOutput(true);	}	// Only JDK: Calling connect will open the connection	conn.connect();//#endif	    	if (qdata != null || qparams != null) {//#ifdef j2me	    os = conn.openOutputStream();//#else	    os = conn.getOutputStream();//#endif	    if(qdata != null) {		//System.err.println("writing " + qdata.getBytes(DEFCHARSET).length + " bytes");		os.write(qdata.getBytes(/*DEFCHARSET*/));	    } else if (qparams != null) {		for(int i=0; i<qparams.length; ++i) {		    //System.err.print("qparams["+i+"]: ");		    //qparams[i].printon(System.err).println("");		    if(i != 0)			os.write('&');		    qparams[i].send(os);		}	    }	    os.flush();	    os.close();	    os = null;	}    }    int getResponseCode() {	try {	    // Only MIDP:	    // Getting the response code will open the connection,	    // send the request, and read the HTTP response headers.	    // The headers are stored until requested.	    return conn.getResponseCode();	}	catch(IOException e) {	    e.printStackTrace();	}	return -1;    }	    Hashtable readHeader() {	Hashtable tab = new Hashtable();	    	// Getting the response fields.	int idx = 0;	// Some implementations may treat the 0th header field as special,	// i.e. as the status line returned by the HTTP server.	// In this case, getHeaderField(0) returns the status line,	// but getHeaderFieldKey(0) returns null.	// For now, it is not clear if this happens on midlets as well.//#ifndef j2me	if (conn.getHeaderFieldKey(0) == null) {	    ++idx;	}//#endif	//System.err.println("--- RESPONSE HEADER-----------------");	String key = "";	while (key != null) {//#ifdef j2me	    try {//#endif		key = conn.getHeaderFieldKey(idx++);		if (key != null) {		    tab.put(key.toLowerCase(), conn.getHeaderField(key));		    //System.err.println("key: " + key + ", value: " + conn.getHeaderField(key));		}//#ifdef j2me	    }	    catch (IOException shouldnothappen) {		shouldnothappen.printStackTrace();	    }//#endif	}	return tab;    }    byte[] readBody() throws IOException {	int len = 0;	byte[] buf = new byte[0];	    //#ifdef j2me	is = conn.openInputStream();	len = (int)conn.getLength();//#else	is = conn.getInputStream();	len = conn.getContentLength();//#endif	    	int bytesread = 0;	int actual = 0;	if (len >= 0) {	    buf = new byte[len];			    while ((bytesread != len) && (actual != -1)) {		actual = is.read(buf, bytesread, len - bytesread);		bytesread += actual;	    }	} else {	    buf = new byte[512];	    do {		if(bytesread == buf.length) {		    byte[] newbuf = new byte[buf.length+512];		    System.arraycopy(buf,0,newbuf,0,bytesread);		    buf = newbuf;		}		actual = is.read(buf, bytesread, buf.length - bytesread);		if(actual > 0)		    bytesread += actual;	    } while(actual > 0);	}	if(bytesread != buf.length) {	    byte[] tmp = new byte[buf.length];	    System.arraycopy(buf,0,tmp,0,bytesread);	    buf = tmp;	}	return buf;    }    void close() {	if (os != null) {	    try {os.close();}	    catch (IOException e) {}	}	if (is != null) {	    try {is.close();}	    catch (IOException e) {}	}	if (conn != null) {//#ifdef j2me	    try {//#endif//#ifndef j2me		conn.disconnect();//#else		conn.close();//#endif//#ifdef j2me	    }	    catch (IOException e) {}//#endif	}    }	//#ifdef j2me    HttpConnection conn;//#else    HttpURLConnection conn;//#endif    boolean secure = false;    InputStream is;    OutputStream os;}

⌨️ 快捷键说明

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