基本信息
源码名称:apache http server
源码大小:3.66KB
文件格式:.rar
开发语言:Java
更新时间:2020-06-01
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpConnectionFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpServerConnection; import org.apache.http.MethodNotSupportedException; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.DefaultBHttpServerConnection; import org.apache.http.impl.DefaultBHttpServerConnectionFactory; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.protocol.UriHttpRequestHandlerMapper; import org.apache.http.util.EntityUtils; import org.w3c.dom.CDATASection; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.sun.net.httpserver.spi.HttpServerProvider; public class ApacheHttpServer { public static void main(String[] args) throws Exception { HttpServerProvider provider = HttpServerProvider.provider(); Map<String ,Object> svcList = parseXml(System.getProperty("user.dir") "/conf.xml"); String ip = (String)((Map<String,Object>)svcList.get("conf")).get("ip"); String port = (String)((Map<String,Object>)svcList.get("conf")).get("port"); String url = (String)((Map<String,Object>)svcList.get("conf")).get("url"); String inst = (String)((Map<String,Object>)svcList.get("conf")).get("inst"); HttpRequestHandler handler = new HttpRequestHandler() { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method " method not supported"); } String entityContent = ""; if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); entityContent = EntityUtils.toString(entity); } String url = request.getRequestLine().getUri(); String svcName = url.substring(url.lastIndexOf("/") 1); // System.out.println("接收报文------" entityContent); String fmt = (String) ((Map<String,Object>)((Map<String,Object>)svcList.get("conf")).get("fmt")).get(svcName); if(null == fmt || "".equals(fmt)) new Exception("未配置报文或xml格式不正确!格式应该是:\r\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<conf>\r\n\t<fmt>\r\n\t\t<服务码>报文内容</服务码>\r\n\t</fmt>\r\n</conf>").printStackTrace();; byte[] sendByte = fmt.trim().getBytes(); response.setEntity(new ByteArrayEntity(sendByte)); response.setEntity(new ByteArrayEntity(fmt.getBytes())); } }; HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("My Response Server 1.1")).add(new ResponseContent()) .add(new ResponseConnControl()).build(); UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register(url, handler); // Set up the HTTP service final HttpService httpService = new HttpService(httpproc, reqistry); final Executor executor = new ThreadPoolExecutor(Integer.parseInt(inst), Integer.parseInt(inst), 100, TimeUnit.SECONDS, // 缓冲队列为5 new ArrayBlockingQueue<Runnable>(50), Executors.defaultThreadFactory(), // new ThreadPoolExecutor.AbortPolicy());//拒绝任务 new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { System.out.println("失败。……。…。……。……。…………"); } }); Thread listener = new Thread() { @Override public void run() { ServerSocket serverSocket = null; HttpConnectionFactory<DefaultBHttpServerConnection> connFactory = null; try { connFactory = DefaultBHttpServerConnectionFactory.INSTANCE; serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress(ip, Integer.parseInt(port)), 500); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } while (!Thread.interrupted()) { try { // Set up HTTP connection Socket socket = serverSocket.accept(); final HttpServerConnection conn = connFactory.createConnection(socket); executor.execute(new Runnable() { @Override public void run() { HttpContext context = new BasicHttpContext(null); try { if (!Thread.interrupted() && conn.isOpen()) { httpService.handleRequest(conn, context); } } catch (ConnectionClosedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (HttpException e) { e.printStackTrace(); } finally { try { if (conn != null) { conn.shutdown(); } } catch (IOException e) { e.printStackTrace(); } } } }); } catch (InterruptedIOException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }; listener.setDaemon(false); listener.start(); } private static Map<String, Object> parseXml(String xmlPath) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance(); DocumentBuilder dombuilder = domfac.newDocumentBuilder(); File file = new File(xmlPath); Document doc = dombuilder.parse(file); Node node = doc.getChildNodes().item(0); return getNodes(node); } private static Map<String, Object> getNodes(Node element) { Map<String, Object> rootMap = new LinkedHashMap<String, Object>(); // ---------------------属性------------------------- NamedNodeMap attMap = element.getAttributes(); Map<String, Object> attAndNodeMap = new LinkedHashMap<String, Object>(); rootMap.put(element.getNodeName(), attAndNodeMap); for (int i = 0; attMap != null && i < attMap.getLength(); i ) { Node nodes = attMap.item(i); String attName = nodes.getNodeName(); String attValue = nodes.getNodeValue(); attAndNodeMap.put(attName, attValue); } // ---------------------节点------------------------- NodeList nodes = element.getChildNodes(); for (int k = 0; k < nodes.getLength(); k ) { if (nodes.item(k).getNodeType() == Node.ELEMENT_NODE) { Node node = nodes.item(k); String oldKey = ""; if (node.getChildNodes() != null && (node.getChildNodes().getLength() > 1 || node.getAttributes().getLength() > 0)) { Map<String, Object> subMap = getNodes(node); if (!subMap.isEmpty()) { oldKey = subMap.keySet().iterator().next(); } if (attAndNodeMap.containsKey(oldKey)) { if (attAndNodeMap.get(oldKey) != null && attAndNodeMap.get(oldKey) instanceof List) { ((List) attAndNodeMap.get(oldKey)).add(subMap.get(oldKey)); } else { List<Object> list = new ArrayList<Object>(); list.add(subMap.get(oldKey)); list.add(attAndNodeMap.get(oldKey)); attAndNodeMap.remove(oldKey); attAndNodeMap.put(oldKey, list); } } else attAndNodeMap.putAll(subMap); } else{ attAndNodeMap.put(node.getNodeName(), node.getTextContent()); } }if(nodes.item(k).getNodeType() == Node.CDATA_SECTION_NODE){ CDATASection cdataNode = (CDATASection) nodes.item(k); String content = cdataNode.getTextContent(); if(attAndNodeMap.isEmpty()){ rootMap.remove(element.getNodeName()); rootMap.put(cdataNode.getParentNode().getNodeName(), content); }else{ rootMap.put(nodes.item(k).getParentNode().getNodeName(), content); } } } return rootMap; } }