嵌入式运行HttpServer

[b]一、嵌入式运行Jetty并提供上传文件功能[/b]
[b]1、定义处理请求的Handler[/b]

public class DispatchRequestHandler extends AbstractHandler {

public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
if(target.contains("/upload")){//process file upload
processUploadFileRequest(request, response);
}else{//other request
response.getWriter().println("<h1>Hello World</h1>");
response.getWriter().println("<li>Request url: " + target + "</li>");
response.getWriter().println("<li>Server port: " + request.getServerPort() + "</li>");
}
}

private void processUploadFileRequest(HttpServletRequest request, HttpServletResponse response){
try{
String uploadPath = "D:/upload";
File uploadFolder = new File(uploadPath);
if(!uploadFolder.exists()){
uploadFolder.mkdirs();
}
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
throw new Exception("not file upload request!");
}
DiskFileItemFactory factory = new DiskFileItemFactory();
//factory.setSizeThreshold(4094);
//factory.setRepository(new File("D:/temp/buffer"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(10*1024*1024);

FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
File savedFile = new File(uploadPath, item.getName());
FileOutputStream fos = new FileOutputStream(savedFile);
byte[] buff = new byte[1024];
int len = 0;
while((len = stream.read(buff)) > 0){
fos.write(buff, 0, len);
}
fos.close();
}
}
/*
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> it = items.iterator();
while(it.hasNext()){
FileItem item = (FileItem)it.next();
if(item.isFormField()){
System.out.print(item.getFieldName()+"="+item.getString());
}else{
String fileName = item.getName();
//item.getInputStream();
System.out.println(fileName);
if(fileName != null){
File savedFile = new File(uploadPath, fileName);
item.write(savedFile);
}
}
}
*/
response.getWriter().println("1");//success
}catch(Exception e){
e.printStackTrace();
try{
response.getWriter().println("0");//fail
}catch(Exception ex){}
}
}

}

[b]2、嵌入式运行Jetty[/b]

public class MainEntrance {

public static void main(String[] args){
Server server = new Server();//jetty server
SelectChannelConnector connector_1 = new SelectChannelConnector();
connector_1.setPort(8088);
SelectChannelConnector connector_2 = new SelectChannelConnector();
connector_2.setPort(8089);
server.setConnectors(new Connector[]{connector_1,connector_2});
server.setHandler(new DispatchRequestHandler());

try {
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}

}

[b]3、用HttpClient上传文件进行测试[/b]

public class TestUpload {

public static void main(String[] args) {
String targetURL = "http://127.0.0.1:8088/upload";
File uploadFile = new File("D:/test/IMG_5352.JPG");
HttpClient httpClient = new DefaultHttpClient();//apache httpClient
HttpPost httpPost = new HttpPost(targetURL);

try {
FileBody fileBody = new FileBody(uploadFile);
StringBody comment = new StringBody("测试上传文件",Charset.forName("UTF-8"));

MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("upload", fileBody);
multipartEntity.addPart("comment", comment);
httpPost.setEntity(multipartEntity);

HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK){
HttpEntity resEntity = response.getEntity();
System.out.println(EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.getConnectionManager().shutdown();
} catch (Exception ignore) {

}
}

}

}

[b]二、JDK6自带的HttpServer[/b]
[b]1.Server端[/b]

public class JDK6HTTPServer {

public static void run(){
try{
HttpServerProvider provider = HttpServerProvider.provider();
HttpServer httpServer = provider.createHttpServer(new InetSocketAddress(80),100);//concurrent request 100
httpServer.createContext("/", new JDK6HTTPServer().new JDK6HTTPServerHandler());
httpServer.setExecutor(null);//creates a default executor
httpServer.start();
System.out.println("JDK6HTTPServer started...");
}catch(Exception e){

}
}

public class JDK6HTTPServerHandler implements HttpHandler{
public void handle(HttpExchange httpExchange) throws IOException {
//System.out.println(httpExchange.getRequestURI());
InputStream inputStrean = httpExchange.getRequestBody();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStrean));
String temp = null;
while((temp = reader.readLine()) != null){
System.out.println("client request:"+temp);
}

StringBuffer buff = new StringBuffer();
buff.append("<h1>Hello World</h1>");
httpExchange.sendResponseHeaders(200, buff.toString().getBytes().length);
OutputStream outputStream = httpExchange.getResponseBody();
outputStream.write(buff.toString().getBytes());
outputStream.close();
}
}

public static void main(String[] args){
run();
}

}

[b]2.client端测试[/b]

public class TestJDK6HTTPServer {

public static void requestServer(){
try{
URL url = new URL("http://127.0.0.1");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setRequestMethod("POST");

String msg = "测试内容";
OutputStream out = urlConn.getOutputStream();
out.write(msg.getBytes());
out.flush();
if(urlConn.getContentLength() != -1 && urlConn.getResponseCode() == 200) {
InputStream in = urlConn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String temp = "";
while ((temp = reader.readLine()) != null) {
System.err.println("server response:" + temp);
}
reader.close();
in.close();
urlConn.disconnect();
}
}catch(Exception e){
e.printStackTrace();
}
}

public static void main(String[] args){
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 20; i++) {
Runnable run = new Runnable() {
public void run() {
requestServer();
}
};
exec.execute(run);
}
exec.shutdown();
}

}
httpkit是精巧的java嵌入式http服务器,超快的启动速度(实测仅需80毫秒),是tomcat、jetty的完美替代方案。 使用方法//起一个server实例 int port = 7777; HttpServer server = HttpServer.bind(port); //设置上下文路径 server.setContextPath("root"); //设置controller类的扫描包 server.packageSearchAndInit("com.lnwazg.main.ctrl"); //设置自动磁盘扫描 server.autoSearchThenAddWatchResourceDirRoute(); //监听在这个端口处 server.listen(); 然后访问文件列表: http://127.0.0.1:7777/root/list 访问具体的控制器 http://127.0.0.1:7777/root/base/index Controller类的写法package com.lnwazg.main.ctrl; import java.io.File; import java.util.ArrayList; import java.util.List; import com.lnwazg.httpkit.anno.BasePath; import com.lnwazg.httpkit.controller.Controller; /**  * 示例controller<br>  * 注解指定这个类的path  * @author nan.li  * @version 2016年11月30日  */ @BasePath("/base") public class FirstController extends Controller {     void index()     {         Person person = new Person();         person.age = "18";         person.name = "hudson";         List<Person> list = new ArrayList<>();         for (int i = 0; i < 5; i )         {             list.add(person);         }         person = new Person();         person.name = getParam("fff");         list.add(person);                  //输出abc         ok("abc");                  //输出一个json对象         //okJson(list);                  //        okJson(GsonHelper.gson.toJson(list));         //        okJson(list);         //        okJson(new FrontObj().success().setData(list));         //        okJson(success(list));         //        okJson(fail(list));         //        okJson(fail(list,10002,"转换错误"));         //        okJson(fail(10002, "转换错误"));         //        okJson(fail(10003));     }          void index2()     {         //输出一个文件         okFile(new File("c:\\1.jpg"));     }          public static class Person     {         String name;                  String age;     } } 标签:httpkit
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值