在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例Java语言基础 → apache http server

apache http server

Java语言基础

下载此实例
  • 开发语言:Java
  • 实例大小:3.66KB
  • 下载次数:11
  • 浏览次数:116
  • 发布时间:2020-06-01
  • 实例类别:Java语言基础
  • 发 布 人:1751002
  • 文件格式:.rar
  • 所需积分:2
 相关标签: Server http PAC TP

实例介绍

【实例简介】

【实例截图】

from clipboard

【核心代码】

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

标签: Server http PAC TP

实例下载地址

apache http server

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警