java HttpServer構建http伺服器
package com.tdt.server.httpserver; import java.io.IOException; import java.net.InetSocketAddress; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.spi.HttpServerProvider; /** * * @author chuer * @Description: 伺服器啟動類 * @date 2014年11月12日 下午3:53:38 * @version V1.0 */ public class MyHttpServer { //啟動服務,監聽來自客戶端的請求 public static void start() throws IOException { Context.load(); HttpServerProvider provider = HttpServerProvider.provider(); HttpServer httpserver =provider.createHttpServer(new InetSocketAddress(8080), 100);//監聽埠8080,能同時接 受100個請求 httpserver.createContext(Context.contextPath, new MyHttpHandler()); httpserver.setExecutor(null); httpserver.start(); System.out.println("server started"); } public static void main(String[] args) throws IOException { start(); } }
package com.tdt.server.httpserver; import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.tdt.server.httpserver.core.Handler; import com.tdt.server.httpserver.core.impl.HttpRequest; import com.tdt.server.httpserver.core.impl.HttpResponse; /** * @author chuer * @Description: 內部訊息處理類 * @date 2014年11月12日 下午3:53:44 * @version V1.0 */ public class MyHttpHandler implements HttpHandler { public void handle(HttpExchange httpExchange) throws IOException { HttpRequest request = new HttpRequest(httpExchange); HttpResponse response = new HttpResponse(httpExchange); Handler handler = Context.getHandler(request.getReuestURI().getPath()); handler.service(request, response); } }
package com.tdt.server.httpserver; import java.util.HashMap; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.tdt.server.httpserver.core.impl.HttpHandler; import com.tdt.server.httpserver.utils.XmlUtils; /** * * @author chuer * @Description: 上下文 * @date 2014年11月12日 下午3:53:48 * @version V1.0 */ public class Context { private static Map<String,HttpHandler> contextMap = new HashMap<String,HttpHandler>(); public static String contextPath = ""; public static void load(){ try{ Document doc = XmlUtils.load(Context.class.getResource("/").getPath()+"context.xml"); Element root = doc.getDocumentElement(); contextPath = XmlUtils.getAttribute(root,"context"); Element[] handlers = XmlUtils.getChildrenByName(root, "handler"); for(Element ele : handlers){ String handle_class = XmlUtils.getChildText(ele, "handler-class"); String url_pattern = XmlUtils.getChildText(ele, "url-pattern"); Class<?> cls = Class.forName(handle_class); Object newInstance = cls.newInstance(); if(newInstance instanceof HttpHandler){ contextMap.put(contextPath+url_pattern, (HttpHandler)newInstance); } } }catch(Exception e){ e.printStackTrace(); } } /** * * @param key * @return */ public static HttpHandler getHandler(String key){ return contextMap.get(key); } }
<?xml version="1.0" encoding="UTF-8"?>
<httpServer context="/myApp">
<handler>
<handler-class>com.tdt.server.httpserver.sample.FirstHandler</handler-class>
<url-pattern>/firstHandler</url-pattern>
</handler>
</httpServer>
package com.tdt.server.httpserver.core;
/**
*
* @author chuer
* @Description: 相應類介面
* @date 2014年11月12日 下午3:54:02
* @version V1.0
*/
public interface Response {
public void write(String result);
}
package com.tdt.server.httpserver.core;
import java.net.URI;
/**
* @author chuer
* @Description: 請求介面
* @date 2014年11月12日 下午3:54:58
* @version V1.0
*/
public interface Request {
public final static String GET = "GET";
public final static String POST = "POST";
public String getParamter(String param);
public String getMethod();
public URI getReuestURI();
public void initRequestHeader();
public void initRequestParam();
public void initRequestBody();
public String getRequestBody();
}
package com.tdt.server.httpserver.core;
/**
* @author chuer
* @Description: 訊息處理介面
* @date 2014年11月12日 下午3:55:10
* @version V1.0
*/
public interface Handler {
public void service(Request request, Response response);
public void doGet(Request request, Response response);
public void doPost(Request request, Response response);
}
package com.tdt.server.httpserver.core.impl;
import com.tdt.server.httpserver.core.Handler;
import com.tdt.server.httpserver.core.Request;
import com.tdt.server.httpserver.core.Response;
public abstract class HttpHandler implements Handler {
@Override
public void service(Request request, Response response) {
request.initRequestHeader();
request.initRequestParam();
if(request.getMethod().equals(Request.GET)){
doGet(request,response);
}else if(request.getMethod().equals(Request.POST)){
request.initRequestBody();
doPost(request,response);
}
}
@Override
public abstract void doGet(Request request, Response response);
@Override
public abstract void doPost(Request request, Response response);
}
package com.tdt.server.httpserver.core.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sun.net.httpserver.HttpExchange;
import com.tdt.server.httpserver.core.Request;
public class HttpRequest implements Request {
private HttpExchange httpExchange;
private Map<String, String> paramMap = new HashMap<String, String>();
private Map<String, List<String>> headMap = new HashMap<String, List<String>>();
private String requestBody = "";
public HttpRequest(HttpExchange httpExchange) {
this.httpExchange = httpExchange;
}
@Override
public String getParamter(String param) {
return paramMap.get(param);
}
@Override
public String getMethod() {
return httpExchange.getRequestMethod().trim().toUpperCase();
}
@Override
public URI getReuestURI() {
return httpExchange.getRequestURI();
}
@Override
public void initRequestParam() {
String query = getReuestURI().getQuery();
String [] arrayStr = query.split("&");
for(String str : arrayStr){
paramMap.put(str.split("=")[0], str.split("=")[1]);
}
}
@Override
public void initRequestHeader() {
for(String s : httpExchange.getRequestHeaders().keySet()){
headMap.put(s, httpExchange.getRequestHeaders().get(s));
}
}
@Override
public void initRequestBody() {
InputStream in = httpExchange.getRequestBody(); // 獲得輸入流
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String temp = null;
try {
while ((temp = reader.readLine()) != null) {
requestBody += temp;
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String getRequestBody() {
return requestBody;
}
public static void main(String[] args) {
String query = "aaa=aaa&bbb=bbb";
String [] a = query.split("&");
for(String s : a){
System.out.print(s.split("=")[0]+"=");
System.out.println(s.split("=")[1]);
}
}
}
package com.tdt.server.httpserver.core.impl;
import java.io.IOException;
import java.io.OutputStream;
import com.sun.net.httpserver.HttpExchange;
import com.tdt.server.httpserver.core.Response;
public class HttpResponse implements Response{
private HttpExchange httpExchange;
public HttpResponse(HttpExchange httpExchange){
this.httpExchange = httpExchange;
}
@Override
public void write(String result) {
try {
httpExchange.sendResponseHeaders(200, result.length());// 設定響應頭屬性及響應資訊的長度
OutputStream out = httpExchange.getResponseBody(); // 獲得輸出流
out.write(result.getBytes());
out.flush();
httpExchange.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.tdt.server.httpserver.sample;
import com.tdt.server.httpserver.core.Request;
import com.tdt.server.httpserver.core.Response;
import com.tdt.server.httpserver.core.impl.HttpHandler;
public class FirstHandler extends HttpHandler{
@Override
public void doGet(Request request, Response response) {
System.out.println("doGet");
System.out.println(request.getParamter("aaa"));
System.out.println(request.getParamter("bbb"));
response.write("helloWorld.....");
}
@Override
public void doPost(Request request, Response response) {
System.out.println("doPost");
System.out.println(request.getRequestBody());
response.write("helloWorld.....");
}
}
顯示hello world....
XmlUtils類是用來解析xml檔案的,沒有放到這裡.
重定向程式碼例項:
<pre class="java" name="code">Headers responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.add("location", "http://www.baidu.com");
httpExchange.sendResponseHeaders(302, 0);
httpExchange.close();
OutputStream out = httpExchange.getResponseBody();
out.write(result.getBytes());
out.flush();
工具類:
package com.tdt.server.httpserver.utils;
import java.io.CharArrayReader;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* <p>
* Title: XmlUtils
* </p>
* <p>
* Description: XML檔案處理工具
* </p>
* <p>
* Copyright: Copyright (c) 2008
* </p>
* <p>
* Company: Ocean Blue Mobile Tech.
* </p>
*
* @author chur
* @version 1.0
*/
public class XmlUtils {
public static final String BR = System.getProperty("line.separator");
/**
* load a xml file from OS file system and interpret it into a Document no
* charset limited
*
* @param xmlfile
* String 檔案路徑名
* @return Document
* @throws Exception
*/
public static Document load(String xmlfile) throws Exception {
javax.xml.parsers.DocumentBuilderFactory factory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(false);
factory.setIgnoringElementContentWhitespace(false);
factory.setValidating(false);
factory.setCoalescing(false);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(xmlfile);
}
/**
* load a xml file from OS file system and interpret it into a Document no
* charset limited
*
* @param xmlfile
* String 檔案路徑名
* @return Document
* @throws Exception
*/
public static Document load(File xmlfile) throws Exception {
javax.xml.parsers.DocumentBuilderFactory factory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(false);
factory.setIgnoringElementContentWhitespace(false);
factory.setValidating(false);
factory.setCoalescing(false);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(xmlfile);
}
/**
* 取得檔名
*
* @param filePath
* String
* @return String
*/
public static String getFileName(String filePath) {
Pattern p = Pattern.compile("[^\\" + File.separator + "]+.xml");
Matcher m = p.matcher(filePath);
if (m.find()) {
return m.group().substring(0, m.group().length() - 4);
}
return "";
}
/**
* 驗證檔名是否合法
*
* @param filePath
* String
* @return String
*/
public static boolean checkValidity(String filePath) {
String[] array = filePath.split(".");
if (array[array.length - 1].equals("xml")) {
return true;
} else {
return false;
}
}
public static boolean isXml(String file) {
if (file.toLowerCase().endsWith("xml")) {
return true;
} else {
return false;
}
}
/**
* load a String without the title tag of xml into a Document
*
* @param domContent
* String 沒有head的XML內容
* @return Document
* @throws Exception
*/
public static Document loadStringWithoutTitle(String domContent)
throws Exception {
domContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + BR
+ domContent;
return XmlUtils.loadString(domContent);
}
/**
* load a String with a title tag of xml into a Document
*
* @param domContent
* String XML內容
* @return Document
* @throws Exception
*/
public static Document loadString(String domContent) throws Exception {
javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(false);
factory.setIgnoringElementContentWhitespace(false);
factory.setValidating(false);
factory.setCoalescing(false);
DocumentBuilder builder = factory.newDocumentBuilder();
char[] chars = new char[domContent.length()];
domContent.getChars(0, domContent.length(), chars, 0);
InputSource is = new InputSource(new CharArrayReader(chars));
return (builder.parse(is));
}
/**
* 根據完整路徑得到整個文件的一個子節點的文字
*
* @param doc
* Document 文件
* @param fullname
* String 子節點完整路徑
* @return String
*/
public static String getTextByFullName(Document doc, String fullname) {
String path[] = StringUtils.toStringArray(fullname, ".");
Element e = doc.getDocumentElement();
for (int i = 1; i < path.length; i++) {
e = getChildByName(e, path[i]);
}
return getText(e);
}
/**
* 根據完整路徑得到某個節點的一個子節點的文字
*
* @param parent
* Element 父節點
* @param fullname
* String 子節點完整路徑
* @return String
*/
public static String getTextByFullName(Element parent, String fullname) {
String path[] = StringUtils.toStringArray(fullname, ".");
Element e = parent;
for (int i = 0; i < path.length; i++) {
e = getChildByName(e, path[i]);
}
return getText(e);
}
/**
* 根據一個document物件獲取某節點下的property的內容
* @param parent
* Element
* @param name
* String
* @return String
*/
public static String getChildText(Element parent, String name) {
Element e = getChildByName(parent, name);
if (e == null) {
return "";
}
return getText(e);
}
/**
* 根據名稱得到一個父節點下所有的子節點
*
* @param e
* Element
* @param name
* String
* @return Element[]
*/
public static Element[] getChildrenByName(Element e, String name) {
NodeList nl = e.getChildNodes();
int max = nl.getLength();
LinkedList<Node> list = new LinkedList<Node>();
for (int i = 0; i < max; i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE
&& n.getNodeName().equals(name)) {
list.add(n);
}
}
return list.toArray(new Element[list.size()]);
}
/**
* 根據名字查詢某個節點下的符合該名字的節點
*
* @param e
* Element 父節點
* @param name
* String 子節點名稱
* @return Element
*/
public static Element getChildByName(Element e, String name) {
Element[] list = getChildrenByName(e, name);
if (list.length == 0) {
return null;
}
if (list.length > 1) {
throw new IllegalStateException("Too many (" + list.length + ") '"
+ name + "' elements found!");
}
return list[0];
}
/**
* 得到一個節點的文字
*
* @param e
* Element
* @return String
*/
public static String getText(Element e) {
NodeList nl = e.getChildNodes();
int max = nl.getLength();
for (int i = 0; i < max; i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.TEXT_NODE) {
return n.getNodeValue();
}
}
return "";
}
public static String getAttribute(Element e, String name) {
return e.getAttribute(name);
}
/**
* get Int value
*
* @param player
* @param name
* @return
*/
public static int getIntValue(Element e) {
return Integer.valueOf(getText(e));
}
/**
* get byte value
*
* @param player
* @param name
* @return
*/
public static byte getByteValue(Element e) {
return Byte.valueOf(getText(e));
}
/**
* 獲取Properties格式的xml資料
*
* @param root
* @return
*/
public static Map<String, Object> getProperties(Element root) {
Map<String, Object> map = new HashMap<String, Object>();
Element[] list = getChildrenByName(root, "property");
for (int i = 0; i < list.length; i++) {
String name = list[i].getAttribute("name");
String type = list[i].getAttribute("type");
String valueString = getText(list[i]);
try {
Class<?> cls = Class.forName(type);
Constructor<?> con = cls.getConstructor(new Class<?>[] { String.class
});
Object value = con.newInstance(new Object[] { valueString
});
map.put(name, value);
} catch (Exception e) {
System.err.println("Unable to parse property '" + name +
"'='" + valueString + "': " + e.toString());
}
}
return map;
}
/**
* 將dom中的內容存入xmlfile所指的檔案中。 dom==null時,xml檔案也是空的。
*
* @param xmlfile
* java.lang.String 儲存的檔名
* @param doc
* ort.w3c.dom.Document 需要儲存的DOM
* @throws Exception
* 任何異常
*/
public static void save(String xmlfile, Document doc) throws Exception {
// 首先建立一個DOMSource物件,該建構函式的引數可以是一個Document物件
// doc代表更改後的DOM Tree。
DOMSource doms = new DOMSource(doc);
// 建立一個File物件,代表DOM Tree所包含的資料的輸出介質,這是一個XML檔案。
File f = new File(xmlfile);
File dir = f.getParentFile();
dir.mkdirs();
// 建立一個StreamResult物件,該建構函式的引數可以取為File物件。
StreamResult sr = new StreamResult(f);
// 下面呼叫JAXP中的XSLT引擎來實現輸出DOM Tree中的資料到XML檔案中的功能。
// XSLT引擎的輸入為DOMSource物件,輸出為StreamResut物件。
try {
// 首先建立一個TransformerFactory物件,再由此建立Transformer物件。Transformer
// 類相當於一個XSLT引擎。通常我們使用它來處理XSL檔案,但是在這裡我們使
// 用它來輸出XML文件。
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
// 設定新的輸出屬性:輸出字元編碼為UTF-8,XSLT引擎所輸出
// 的XML文件如果包含了中文字元,可以正常顯示,不會出現所謂的"漢字問題"。
// 請留意OutputKeys類的字串常數OutputKeys.ENCODING。
Properties properties = t.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING, "UTF-8");
properties.setProperty(OutputKeys.INDENT, "yes");
// 更新XSLT引擎的輸出屬性。
t.setOutputProperties(properties);
// 關鍵的一步, 呼叫Transformer物件 (XSLT引擎)的transform()方法,該方法的第一
// 個引數是DOMSource物件,第二個引數是StreamResult物件。
t.transform(doms, sr);
} catch (TransformerConfigurationException tce) {
tce.printStackTrace();
} catch (TransformerException te) {
te.printStackTrace();
}
}
/**
* create a blank Document.
*
* @param rootElementName
* String
* @return Document
* @throws Exception
*/
public static Document blankDocument(String rootElementName)
throws Exception {
javax.xml.parsers.DocumentBuilderFactory factory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(false);
factory.setIgnoringElementContentWhitespace(false);
factory.setValidating(false);
factory.setCoalescing(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement(rootElementName);
doc.appendChild(root);
return doc;
}
public static Element createChild(Document doc, Element root, String name) {
Element elem = doc.createElement(name);
root.appendChild(elem);
return elem;
}
public static void createChildText(Document doc, Element elem, String name,
String value) {
Element child = doc.createElement(name);
child.appendChild(doc.createTextNode(value == null ? "" : value));
elem.appendChild(child);
}
/**
* 建立一個帶註釋的子節點
*
* @param doc
* Document
* @param elem
* Element
* @param name
* String
* @param value
* String
* @param comment
* String
*/
public static void createChildTextWithComment(Document doc, Element elem,
String name, String value, String comment) {
Element child = doc.createElement(name);
child.appendChild(doc.createTextNode(value == null ? "" : value));
Comment c = doc.createComment(comment);
elem.appendChild(c);
elem.appendChild(child);
}
/**
* 建立一段註釋
*
* @param doc
* Document
* @param comment
* String
*/
public static void createComment(Document doc, String comment) {
Comment c = doc.createComment(comment);
doc.getDocumentElement().appendChild(c);
}
public static void createOptionalChildText(Document doc, Element elem,
String name, String value) {
if (value == null || value.length() == 0) {
return;
}
Element child = doc.createElement(name);
child.appendChild(doc.createTextNode(value));
elem.appendChild(child);
}
public static void applyProperties(Object o, Element root) {
Map<String,Object> map = getProperties(root);
Iterator<String> it = map.keySet().iterator();
Field[] fields = o.getClass().getFields();
Method[] methods = o.getClass().getMethods();
while (it.hasNext()) {
String name = (String) it.next();
Object value = map.get(name);
try {
for (int i = 0; i < fields.length; i++) {
if (fields[i].getName().equalsIgnoreCase(name) && isTypeMatch(fields[i].getType(),
value.getClass())) {
fields[i].set(o, value);
System.err.println("Set field " + fields
[i].getName() + "=" + value);
break;
}
}
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equalsIgnoreCase("set" + name) && methods[i].getParameterTypes
().length == 1 && isTypeMatch(methods
[i].getParameterTypes()[0], value.getClass())) {
methods[i].invoke(o, new Object[] { value
});
System.err.println("Set method " + methods
[i].getName() + "=" + value);
break;
}
}
} catch (Exception e) {
System.err.println("Unable to apply property '" + name + "': " + e.toString());
}
}
}
private static boolean isTypeMatch(Class<?> one, Class<?> two) {
if (one.equals(two)) {
return true;
}
if (one.isPrimitive()) {
if (one.getName().equals("int") && two.getName().equals("java.lang.Integer")) {
return true;
}
if (one.getName().equals("long") && two.getName().equals("java.lang.Long")) {
return true;
}
if (one.getName().equals("float") && two.getName().equals("java.lang.Float")) {
return true;
}
if (one.getName().equals("double") && two.getName().equals("java.lang.Double")) {
return true;
}
if (one.getName().equals("char") && two.getName().equals("java.lang.Character")) {
return true;
}
if (one.getName().equals("byte") && two.getName().equals("java.lang.Byte")) {
return true;
}
if (one.getName().equals("short") && two.getName().equals("java.lang.Short")) {
return true;
}
if (one.getName().equals("boolean") && two.getName().equals("java.lang.Boolean")) {
return true;
}
}
return false;
}
}
package com.tdt.server.httpserver.utils;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
/**
* Converts a line of text into an array of lower case words. Words are
* delimited by the following characters: , .\r\n:/\+
* <p>
* In the future, this method should be changed to use a
* BreakIterator.wordInstance(). That class offers much more fexibility.
*
* @param text
* a String of text to convert into an array of words
* @return text broken up into an array of words.
*/
public static final String[] toLowerCaseWordArray(String text) {
if (text == null || text.length() == 0) {
return new String[0];
}
StringTokenizer tokens = new StringTokenizer(text, " ,\r\n.:/\\+");
String[] words = new String[tokens.countTokens()];
for (int i = 0; i < words.length; i++) {
words[i] = tokens.nextToken().toLowerCase();
}
return words;
}
/**
* Converts a line of text into an array of lower case words. Words are
* delimited by the following characters: , .\r\n:/\+
* <p>
* In the future, this method should be changed to use a
* BreakIterator.wordInstance(). That class offers much more fexibility.
*
* @param text
* a String of text to convert into an array of words
* @return text broken up into an array of words.
*/
public static final String[] toStringArray(String text) {
if (text == null || text.length() == 0) {
return new String[0];
}
StringTokenizer tokens = new StringTokenizer(text, ",\r\n/\\");
String[] words = new String[tokens.countTokens()];
for (int i = 0; i < words.length; i++) {
words[i] = tokens.nextToken();
}
return words;
}
/**
* * Converts a line of text into an array of lower case words. Words are
* delimited by the following characters: , .\r\n:/\+
* <p>
* In the future, this method should be changed to use a
* BreakIterator.wordInstance(). That class offers much more fexibility.
*
* @param text
* a String of text to convert into an array of words
* @param token
* String
* @return String[]broken up into an array of words.
*/
public static final String[] toStringArray(String text, String token) {
if (text == null || text.length() == 0) {
return new String[0];
}
StringTokenizer tokens = new StringTokenizer(text, token);
String[] words = new String[tokens.countTokens()];
for (int i = 0; i < words.length; i++) {
words[i] = tokens.nextToken();
}
return words;
}
/**
*
* @param source
* @return
*/
public static String[] splitOnWhitespace(String source) {
int pos = -1;
LinkedList<String> list = new LinkedList<String>();
int max = source.length();
for (int i = 0; i < max; i++) {
char c = source.charAt(i);
if (Character.isWhitespace(c)) {
if (i - pos > 1) {
list.add(source.substring(pos + 1, i));
}
pos = i;
}
}
return list.toArray(new String[list.size()]);
}
/**
* Replayer str
*
* @param str
* @param key
* @param replacement
* @return
*/
public static final String replaceAll(String str, String key,
String replacement) {
if (str != null && key != null && replacement != null
&& !str.equals("") && !key.equals("")) {
StringBuilder strbuf = new StringBuilder();
int begin = 0;
int slen = str.length();
int npos = 0;
int klen = key.length();
for (; begin < slen && (npos = str.indexOf(key, begin)) >= begin; begin = npos
+ klen) {
strbuf.append(str.substring(begin, npos)).append(replacement);
}
if (begin == 0) {
return str;
}
if (begin < slen) {
strbuf.append(str.substring(begin));
}
return strbuf.toString();
} else {
return str;
}
}
public static String UnicodeToString(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
boolean hasU = false;
while (matcher.find()) {
hasU = true;
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
String s = str;
try{
if(!hasU){
int i = 0;
String rstr = "";
while(i+4<=str.length()){
ch = (char) Integer.parseInt(str.substring(i,i=i+4), 16);
rstr = rstr+ch;
}
str = rstr;
}
}catch(Exception ex){
str = s;
ex.printStackTrace();
}
return str;
}
/** 空字串。 */
public static final String EMPTY_STRING = "";
/**
* 比較兩個字串(大小寫敏感)。
* <pre>
* StringUtil.equals(null, null) = true
* StringUtil.equals(null, "abc") = false
* StringUtil.equals("abc", null) = false
* StringUtil.equals("abc", "abc") = true
* StringUtil.equals("abc", "ABC") = false
* </pre>
*
* @param str1 要比較的字串1
* @param str2 要比較的字串2
*
* @return 如果兩個字串相同,或者都是<code>null</code>,則返回<code>true</code>
*/
public static boolean equals(String str1, String str2) {
if (str1 == null) {
return str2 == null;
}
return str1.equals(str2);
}
/**
* 比較兩個字串(大小寫不敏感)。
* <pre>
* StringUtil.equalsIgnoreCase(null, null) = true
* StringUtil.equalsIgnoreCase(null, "abc") = false
* StringUtil.equalsIgnoreCase("abc", null) = false
* StringUtil.equalsIgnoreCase("abc", "abc") = true
* StringUtil.equalsIgnoreCase("abc", "ABC") = true
* </pre>
*
* @param str1 要比較的字串1
* @param str2 要比較的字串2
*
* @return 如果兩個字串相同,或者都是<code>null</code>,則返回<code>true</code>
*/
public static boolean equalsIgnoreCase(String str1, String str2) {
if (str1 == null) {
return str2 == null;
}
return str1.equalsIgnoreCase(str2);
}
/**
* 檢查字串是否是空白:<code>null</code>、空字串<code>""</code>或只有空白字元。
* <pre>
* StringUtil.isBlank(null) = true
* StringUtil.isBlank("") = true
* StringUtil.isBlank(" ") = true
* StringUtil.isBlank("bob") = false
* StringUtil.isBlank(" bob ") = false
* </pre>
*
* @param str 要檢查的字串
*
* @return 如果為空白, 則返回<code>true</code>
*/
public static boolean isBlank(String str) {
int length;
if ((str == null) || ((length = str.length()) == 0)) {
return true;
}
for (int i = 0; i < length; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 檢查字串是否不是空白:<code>null</code>、空字串<code>""</code>或只有空白字元。
* <pre>
* StringUtil.isBlank(null) = false
* StringUtil.isBlank("") = false
* StringUtil.isBlank(" ") = false
* StringUtil.isBlank("bob") = true
* StringUtil.isBlank(" bob ") = true
* </pre>
*
* @param str 要檢查的字串
*
* @return 如果為空白, 則返回<code>true</code>
*/
public static boolean isNotBlank(String str) {
int length;
if ((str == null) || ((length = str.length()) == 0)) {
return false;
}
for (int i = 0; i < length; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
/**
* 檢查字串是否為<code>null</code>或空字串<code>""</code>。
* <pre>
* StringUtil.isEmpty(null) = true
* StringUtil.isEmpty("") = true
* StringUtil.isEmpty(" ") = false
* StringUtil.isEmpty("bob") = false
* StringUtil.isEmpty(" bob ") = false
* </pre>
*
* @param str 要檢查的字串
*
* @return 如果為空, 則返回<code>true</code>
*/
public static boolean isEmpty(String str) {
return ((str == null) || (str.length() == 0));
}
/**
* 檢查字串是否不是<code>null</code>和空字串<code>""</code>。
* <pre>
* StringUtil.isEmpty(null) = false
* StringUtil.isEmpty("") = false
* StringUtil.isEmpty(" ") = true
* StringUtil.isEmpty("bob") = true
* StringUtil.isEmpty(" bob ") = true
* </pre>
*
* @param str 要檢查的字串
*
* @return 如果不為空, 則返回<code>true</code>
*/
public static boolean isNotEmpty(String str) {
return ((str != null) && (str.length() > 0));
}
/**
* 在字串中查詢指定字串,並返回第一個匹配的索引值。如果字串為<code>null</code>或未找到,則返回<code>-1</code>。
* <pre>
* StringUtil.indexOf(null, *) = -1
* StringUtil.indexOf(*, null) = -1
* StringUtil.indexOf("", "") = 0
* StringUtil.indexOf("aabaabaa", "a") = 0
* StringUtil.indexOf("aabaabaa", "b") = 2
* StringUtil.indexOf("aabaabaa", "ab") = 1
* StringUtil.indexOf("aabaabaa", "") = 0
* </pre>
*
* @param str 要掃描的字串
* @param searchStr 要查詢的字串
*
* @return 第一個匹配的索引值。如果字串為<code>null</code>或未找到,則返回<code>-1</code>
*/
public static int indexOf(String str, String searchStr) {
if ((str == null) || (searchStr == null)) {
return -1;
}
return str.indexOf(searchStr);
}
/**
* 在字串中查詢指定字串,並返回第一個匹配的索引值。如果字串為<code>null</code>或未找到,則返回<code>-1</code>。
* <pre>
* StringUtil.indexOf(null, *, *) = -1
* StringUtil.indexOf(*, null, *) = -1
* StringUtil.indexOf("", "", 0) = 0
* StringUtil.indexOf("aabaabaa", "a", 0) = 0
* StringUtil.indexOf("aabaabaa", "b", 0) = 2
* StringUtil.indexOf("aabaabaa", "ab", 0) = 1
* StringUtil.indexOf("aabaabaa", "b", 3) = 5
* StringUtil.indexOf("aabaabaa", "b", 9) = -1
* StringUtil.indexOf("aabaabaa", "b", -1) = 2
* StringUtil.indexOf("aabaabaa", "", 2) = 2
* StringUtil.indexOf("abc", "", 9) = 3
* </pre>
*
* @param str 要掃描的字串
* @param searchStr 要查詢的字串
* @param startPos 開始搜尋的索引值,如果小於0,則看作0
*
* @return 第一個匹配的索引值。如果字串為<code>null</code>或未找到,則返回<code>-1</code>
*/
public static int indexOf(String str, String searchStr, int startPos) {
if ((str == null) || (searchStr == null)) {
return -1;
}
// JDK1.3及以下版本的bug:不能正確處理下面的情況
if ((searchStr.length() == 0) && (startPos >= str.length())) {
return str.length();
}
return str.indexOf(searchStr, startPos);
}
/**
* 取指定字串的子串。
*
* <p>
* 負的索引代表從尾部開始計算。如果字串為<code>null</code>,則返回<code>null</code>。
* <pre>
* StringUtil.substring(null, *, *) = null
* StringUtil.substring("", * , *) = "";
* StringUtil.substring("abc", 0, 2) = "ab"
* StringUtil.substring("abc", 2, 0) = ""
* StringUtil.substring("abc", 2, 4) = "c"
* StringUtil.substring("abc", 4, 6) = ""
* StringUtil.substring("abc", 2, 2) = ""
* StringUtil.substring("abc", -2, -1) = "b"
* StringUtil.substring("abc", -4, 2) = "ab"
* </pre>
* </p>
*
* @param str 字串
* @param start 起始索引,如果為負數,表示從尾部計算
* @param end 結束索引(不含),如果為負數,表示從尾部計算
*
* @return 子串,如果原始串為<code>null</code>,則返回<code>null</code>
*/
public static String substring(String str, int start, int end) {
if (str == null) {
return null;
}
if (end < 0) {
end = str.length() + end;
}
if (start < 0) {
start = str.length() + start;
}
if (end > str.length()) {
end = str.length();
}
if (start > end) {
return EMPTY_STRING;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
/**
* 檢查字串中是否包含指定的字串。如果字串為<code>null</code>,將返回<code>false</code>。
* <pre>
* StringUtil.contains(null, *) = false
* StringUtil.contains(*, null) = false
* StringUtil.contains("", "") = true
* StringUtil.contains("abc", "") = true
* StringUtil.contains("abc", "a") = true
* StringUtil.contains("abc", "z") = false
* </pre>
*
* @param str 要掃描的字串
* @param searchStr 要查詢的字串
*
* @return 如果找到,則返回<code>true</code>
*/
public static boolean contains(String str, String searchStr) {
if ((str == null) || (searchStr == null)) {
return false;
}
return str.indexOf(searchStr) >= 0;
}
/**
* <p>Checks if the String contains only unicode digits.
* A decimal point is not a unicode digit and returns false.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty String ("") will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if only contains digits, and is non-null
*/
public static boolean isNumeric(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* 字串拼接
* @param object
* @return
*/
public static String assemble(char sep,Object... object){
if(object == null)return null;
StringBuilder sb = new StringBuilder();
for(Object obj:object){
if(obj == null)obj="";
sb.append(obj.toString()).append(sep);
}
String str = "";
if(sb.length()>0){
str = sb.substring(0, sb.length()-1);
}
return str;
}
// 6-16個字母和數字組成
private static String regex = "^[A-Za-z0-9]$";
/**
* 檢測字串是否符合規則(6-16個字母和數字組成,大小寫不敏感)
* @param user
* @return
*/
public static boolean checkStringLegal(String user) {
boolean isMatch = true;
char[] userChars = user.toCharArray();
for(char c : userChars){
isMatch = String.valueOf(c).matches(regex);
if(!isMatch){
break;
}
}
return isMatch;
}
public static String getString(String input) {
return getString(input, true, "");
}
public static String getString(String input, boolean btrim, String dval) {
if (input == null)
return dval;
try {
if (btrim)
return trim(input);
else
return input;
} catch (Exception e) {
return "";
}
}
public static String Trim(String str) {
return trim(str);
}
public static String[] Trim(String[] s) {
return trim(s);
}
public static String trim(String str) {
if (str == null)
return "";
else
return str.trim();
}
public static String[] trim(String[] s) {
if (s == null || s.length <= 0)
return s;
for (int i = 0; i < s.length; i++)
s[i] = trim(s[i]);
return s;
}
public static int getInt(String input, boolean btrim, int dval) {
if (input == null)
return dval;
int val;
try {
String str = new String(input);
if (btrim)
str = trim(str);
val = Integer.parseInt(str);
} catch (Exception e) {
val = dval;
}
return val;
}
public static int[] getInts(String input) {
return getInts(input, ",");
}
public static int[] getInts(String input, String split) {
if (input == null) {
return null;
}
String[] ss = input.split(split);
int[] ii = new int[ss.length];
for (int i=0;i<ii.length;i++) {
ii[i] = getInt(ss[i]);
}
return ii;
}
public static int getInt(String input) {
return getInt(input, true, 0);
}
}
相關推薦
java HttpServer構建http伺服器
package com.tdt.server.httpserver; import java.io.IOException; import java.net.InetSocketAddress; import com.sun.net.httpserver.HttpSer
採用beego框架構建 http伺服器
beego是一個使用 Go 的思維來快速構建並開發 Go 應用程式的開源http框架,作者是謝孟軍。它可以快速開發API、Web、後端服務等各種應用,功能支援RESTFul,MVC模型;含有智慧路由,內建強大模組,採用了 Go 原生的 http 包來處
JAVA實現簡易HTTP伺服器
說實話,之前完全沒有想過,我還能寫出伺服器。感覺伺服器這麼高階的東西,能會用就不錯了,還能寫。 不吐槽了,開始了。 這次的作業是搭建一個伺服器,要能接收請求,並給瀏覽器返回正確響應。 專案的下載地址 專案目標:實現一個簡易的多執行
基於Java實現簡單Http伺服器之一
本文將詳細介紹如何基於java語言實現一個簡單的Http伺服器,文中將主要介紹三個方面的內容:1)Http協議的基本知識、2)java.net.Socket類、3)java.net.ServerSocket類,讀完本文後你可以把這個伺服器用多執行緒的技術重新編
構建伺服器叢集感知的 Java 應用程式-http://www.ibm.com/developerworks/cn/java/j-zookeeper/
如今,許多企業應用程式都由一組合作的分散式程序和伺服器交付。例如,可向幾乎所有流行的 Java 企業伺服器的 Web 請求提供伺服器叢集功能,這些伺服器還可以提供有限的配置選項,如伺服器權重和配置重新載入。 雖然大多數 Java 企業伺服器具有叢集的內建支援,但對於自定義用例來說,在應用程式級並沒有
Qt Http QHttpMultiPart上傳檔案到java http伺服器
Qt Http QHttpMultiPart上傳檔案到java http伺服器 1.最近專案用到了Qt上傳檔案到HT
JAVA NIO Selector構建簡單伺服器
JAVA NIO Selector構建簡單伺服器 ServerSocketChannel + Selector SocketChannel UnitTest 結果 ServerSocketChannel + Selector NI
JAVA中建立HTTP通訊,從伺服器上獲取HTML程式碼,通過HTTP請求來下載圖片或其他二進位制檔案的程式,下載結果要按下載到的檔案型別進行存檔中。
通過HTTP請求來下載圖片或其他二進位制檔案的程式,下載結果要按下載到的檔案型別進行存檔 將程式碼從伺服器的中獲取下來的程式碼,在我之前已經講過了這裡寫連結內容 這裡我們就直接將原始碼稍加改動,加入一個檔案並請將builder 寫入即可。 import
基於 Java NIO 實現簡單的 HTTP 伺服器
1.簡介 本文是上一篇文章實踐篇,在上一篇文章中,我分析了選擇器 Selector 的原理。本篇文章,我們來說說 Selector 的應用,如標題所示,這裡我基於 Java NIO 實現了一個簡單的 HTTP 伺服器。在接下來的章節中,我會詳細講解 HTTP 伺服器實現的過程。另外,本文所對應的
HTTP 伺服器開發(Java)--HTTP請求
最近由於要課程作業,要做一個HTTP伺服器,現在紀錄下我做這個課程作業的全部過程。 (一)理論知識 HTTP(HyperText Transfer Protocol)是一套計算機通過網路進行通訊的規則。計算機專家設計出HTTP,使HTTP客戶(如
一個簡易的java http伺服器
TTP是個大協議,完整功能的HTTP伺服器必須響應資源請求,將URL轉換為本地系統的資源名。響應各種形式的HTTP請求(GET、POST等)。處理不存在的檔案請求,返回各種形式的狀態碼,解析MIME型別等。但許多特定功能的HTTP伺服器並不需要所有這些功能。例如,很多
使用Java Socket手擼一個http伺服器
原文連線:使用Java Socket手擼一個http伺服器 作為一個java後端,提供http服務可以說是基本技能之一了,但是你真的瞭解http協議麼?你知道知道如何手擼一個http伺服器麼?tomcat的底層是怎麼支援http服務的呢?大名鼎鼎的Servlet又是什麼東西呢,該怎麼使用呢? 在
使用C#開發HTTP伺服器系列之構建RESTful API
各位朋友大家好,我是秦元培,歡迎大家關注我的部落格,我的部落格地址是http://qinyuanpei.com。到目前為止,“使用C#開發HTTP伺服器”這個系列系列文章目前已經接近尾聲了,雖然我們在伺服器功能的完整性(如支援併發、快取、非同步、Htts等)
java構建http連線的工具類
package weiboUtil; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.H
模擬帶Servlet技術的HTTP伺服器的Java實現
上一篇文章說道, Web發展初期, 使用者只能檢視靜態頁面. 隨著Web發展,只能顯示靜態頁面的web顯然已經不能滿足大眾的需求,所以出現了CGI和用Java編寫的Servlet程式. Servlet可以根據使用者的請求動態的生成html頁面,然後發給瀏覽器.
用java搭建自己的http伺服器
原文參考:http://blog.csdn.net/ajaxhu/article/details/12316501# 侵權立刪 瀏覽器開啟網頁可以簡單分為三個階段: 1、通過socket向伺服器傳送一個一定格式的請求字串,字串中會包含使用者輸入的地址。 2、伺服器收
用Java編寫你自己的簡單HTTP伺服器
HTTP是個大協議,完整功能的HTTP伺服器必須響應資源請求,將URL轉換為本地系統的資源名。響應各種形式的HTTP請求(GET、POST等)。處理不存在的檔案請求,返回各種形式的狀態碼,解析MIME型別等。但許多特定功能的HTTP伺服器並不需要所有這些功能。例如,很多網站只
用gradle構建的java專案部署到伺服器
最近剛接觸gradle和爬蟲,把感覺有用的記下來開發工具:eclipse,spring+mybatis+gradle+webmagic前提是本地已經有了一個可以執行的gradle的專案,以下主要介紹怎麼把專案部署到伺服器上。1.改build.gradle檔案build.gra
用JAVA實現一個簡單地Http伺服器
SimpleHttpServer.java import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.So
使用Java實現簡單的Http伺服器
在Java中可以使用HttpServer類來實現Http伺服器,該類位於com.sun.net包下(rt.jar)。實現程式碼如下: 主程式類 package bg.httpserver; import com.sun.net.httpserver.HttpServer; import java.io.IO