Giter VIP home page Giter VIP logo

andserver's Introduction

AndServer

Logo

AndServer is an HTTP and reverse proxy server.

Web server and Web framework of Android platform. It provides annotations like SpringMVC, and if you are familiar with SpringMVC, you can master it very quickly.

  • Static html website deployment.
  • Dynamic http api deployment.
  • Reverse proxy server.

Web Server

Deploy a web server:

Server server = AndServer.webServer(context)
    .port(8080)
    .timeout(10, TimeUnit.SECONDS)
    .build();

// startup the server.
server.startup();

...

// shutdown the server.
server.shutdown();

It also has some features, such as inetAddress(InetAddress), serverSocketFactory(ServerSocketFactory) and sslContext(SSLContext), depending on what you want to achieve.

@RestController
@RequestMapping(path = "/user")
public class UserController {

    @PostMapping("/login")
    public String login(@RequestParam("account") String account,
                        @RequestParam("password") String password) {

        ...
        return "Successful.";
    }

    @GetMapping(path = "/{userId}")
    public User info(@PathVariable("userId") String userId,
                     @QueryParam("fields") String fields) {

        User user = findUserById(userId, fields);
        ...

        return user;
    }

    @PutMapping(path = "/{userId}")
    public void modify(@PathVariable("userId") String userId
                       @RequestParam("age") int age) {
        ...
    }
}

The above code will generate the following two http apis:

POST http://.../user/login
GET http://.../user/uid_001?fields=id,name,age
PUT http://.../user/uid_001

Get connection information with the client:

@GetMapping(path = "/connection")
void getConnection(HttpRequest request, ...) {
    request.getLocalAddr();   // HostAddress
    request.getLocalName();   // HostName
    request.getLocalPort();   // server's port

    request.getRemoteAddr();  // HostAddress
    request.getRemoteHost();  // Especially HostName, second HostAddress
    request.getRemotePort();  // client's port

    ...
}

For documentation and additional information see the website.

Reverse Proxy Server

Deploy a reverse proxy server:

Server server = AndServer.proxyServer()
    .addProxy("www.example1.com", "http://192.167.1.11:8080")
    .addProxy("example2.com", "https://192.167.1.12:9090")
    .addProxy("55.66.11.11", "http://www.google.com")
    .addProxy("192.168.1.11", "https://github.com:6666")
    .port(80)
    .timeout(10, TimeUnit.SECONDS)
    .build();

// startup the server.
server.startup();

...

// shutdown the server.
server.shutdown();

Note: It is just a reverse proxy and does not have the ability to take care of loading balance.

Download

Add the plugin to your project build script :

buildscript {
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.yanzhenjie.andserver:plugin:2.1.12'
        ...
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}
...

And then add AndServer dependency to your module:

apply plugin: 'com.yanzhenjie.andserver'

...

dependencies {
    implementation 'com.yanzhenjie.andserver:api:2.1.12'
    annotationProcessor 'com.yanzhenjie.andserver:processor:2.1.12'
    ...
}

If you are using Kotlin, replace annotationProcessor with kapt.

Contributing

Before submitting pull requests, contributors must abide by the agreement .

License

Copyright Zhenjie Yan

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

andserver's People

Contributors

fsdfc avatar hellofriday avatar kong-jing avatar oddcn avatar xuexiangjys avatar yanzhenjie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

andserver's Issues

AndServer程序崩溃,请教是什么原因?

我把AndServer移到我的Launcher程序里,参考Demo的MainActivity, 在RemoteInstallActivity里启动AndServer, 然后客户端浏览器运行 http://x.x.x.x:8000/test, 这是程序崩溃,Log如下:
--------- beginning of crash
02-27 01:53:44.551 E/AndroidRuntime( 5017): FATAL EXCEPTION: pool-1-thread-1
02-27 01:53:44.551 E/AndroidRuntime( 5017): Process: com.droidlogic.mboxlauncher, PID: 5017
02-27 01:53:44.551 E/AndroidRuntime( 5017): java.lang.AbstractMethodError: abstract method "void org.apache.http.protocol.HttpRequestHandler.handle(org.apache.http.HttpRequest, org.apache.http.HttpResponse, org.apache.http.protocol.HttpContext)"
02-27 01:53:44.551 E/AndroidRuntime( 5017): at org.apache.http.protocol.HttpService.doService(HttpService.java:248)
02-27 01:53:44.551 E/AndroidRuntime( 5017): at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:192)
02-27 01:53:44.551 E/AndroidRuntime( 5017): at com.droidlogic.mboxlauncher.remoteserver.RequestHandleTask.run(RequestHandleTask.java:29)
02-27 01:53:44.551 E/AndroidRuntime( 5017): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
02-27 01:53:44.551 E/AndroidRuntime( 5017): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
02-27 01:53:44.551 E/AndroidRuntime( 5017): at java.lang.Thread.run(Thread.java:818)
02-27 01:53:44.578 W/ActivityManager( 4051): Force finishing activity com.droidlogic.mboxlauncher/.settings.RemoteInstallActivity

请教,从Log上看是HttpRequestHandler.handle导致程序崩溃吗?这里的handler就是AndServer的AndServerTestHandler, 我无法确定是什么原因导致?请教这会是什么原因,或者有什么方法来确定原因?

registerHandler的path能不能用正则表达式?

需要匹配一批URL或者干脆对全部访问的URL进行重定向处理,按我的理解,现在这个没法解决,只能列出有限个registerHandler。

另外完全自定义网站我看官方文档和源码,那个似乎也是继承自registerHandler,似乎也没法解决这一问题。

使用NewStorageWebsite无法正常下载视频@yanzhenjie @ag2s20150909

使用StorageWebsite的时候,HTML是这样的http://172.12.123.23:8000/www/1/2/a/index.html,使用NewStorageWebsite之后,HTML是这样的http://172.12.123.23:8000/index.html,而且可以接收到SD下的存储路径下的视频文件的信息,但是使用StorageWebsite,视频可以正常下载,使用NewStorageWebsite无法正常下载。@yanzhenjie @ag2s20150909
String path = SD卡的目录;
AndServer andServer = new AndServer.Build()
.port(8080)
.timeout(10 * 1000)
.registerHandler("login", new RequestLoginHandler(mData))
.website(new NewStorageWebsite(path))
.build();
mServer = andServer.createServer();

网站的信息,我在assets下有,而且copy到了sd卡,可以使用StorageWebsite,并且使用http://172.12.123.23:8000/www/1/2/a/index.html访问到SD卡里面的视频文件,下载也正常,但是访问index.html的地址太长了!想缩短,用了NewStorageWebsite,但是不能让sd下的视频正常下载,求解,非常感谢!

我的微信fkq339 随时可以联系我。

请问如何在response中返回html格式内容?

请问如何在repsonse中返回html格式内容?我尝试在StringEntity中返回带html标签内容,结果却连html标签都显示出来,在android sdk自带的org.apache.http.legacy.jar里没找到设置ContentType的接口,请教有无方法返回html格式内容?

关于ip地址固定

android 源码中,对于热点的ip是固定的:
NetworkUtils.numericToInetAddress("192.168.43.1"), 24));
但是开启手机热点,运行AndServer中 String ip = NetUtil.getLocalIPAddress();
这个IP的格式是 10.xx.xxx.xx ,并且该ip会改变,请问如何做到固定ip?

只增加了一行代码,这样的逻辑才正常。

import android.text.TextUtils;

import com.yanzhenjie.andserver.RequestHandler;
import com.yanzhenjie.andserver.handler.StorageRequestHandler;
import com.yanzhenjie.andserver.util.StorageWrapper;

import java.io.File;
import java.util.List;
import java.util.Map;

public class NewStorageWebsite extends BasicWebsite {

/**
 * StorageWrapper.
 */
private StorageWrapper mStorageWrapper;

/**
 * Site root directory.
 */
private String mRootPath;

/**
 * Storage Website.
 *
 * @param rootPath site root directory in assets, such as: {@code "/storage/sdcard/google/website"}.
 */
public NewStorageWebsite(String rootPath) {
    super(rootPath);
    if (TextUtils.isEmpty(rootPath)) throw new NullPointerException("The RootPath can not be null.");
    this.mRootPath = trimSlash(rootPath);
    mStorageWrapper = new StorageWrapper();
}

@Override
public void onRegister(Map<String, RequestHandler> handlerMap) {
    RequestHandler indexHandler = new StorageRequestHandler(INDEX_HTML);
    handlerMap.put("", indexHandler);
    handlerMap.put(mRootPath, indexHandler);
    handlerMap.put(mRootPath + File.separator, indexHandler);
    handlerMap.put(mRootPath + File.separator + INDEX_HTML, indexHandler);

    List<String> pathList = mStorageWrapper.scanFile(getHttpPath(mRootPath));
    for (String path : pathList) {
        RequestHandler requestHandler = new StorageRequestHandler(path);
    path=path.substring(path.indexOf(mRootPath)+mRootPath.length(),path.length());
        handlerMap.put(path, requestHandler);
    }
}

}

RequestFileHandler使用

大神,RequestFileHandler这个不知道怎么用,能完善下sample里面的代码吗;我看到这一行注释了

网页上ajax 请求 localhost 被拦截了

最近在网页上做 ajax 请求 localhost 被拦截了,必须要填写固定IP地址吗

<script type="text/javascript">
	$.ajax({
		url : postPath+'/getplat',
		dataType : "json",
		data : {
		},
		type : "GET",
		success : function(result) {
			console.log(result)
		}
	});


</script>

The resource [/] does not exist.

相同的代码:在三星上不支持,是要去注意哪里吗?
报404,意思是链接指向的网页不存在,我明明有copy到sd卡下的。

编译报错

Warning: Exception while processing task java.io.IOException: Can't write [D:\Project\HB\Code\H5\HBAccountant\platforms\android\app\build\intermediates\transforms\proguard\release\jars\3\1f\main.jar] (Can't read
[D:\Program Files\Android-sdk\.android\build-cache\d2f36575cd9c84b7de7e7e192870487827fca117\output\jars\libs\org.apache.http.legacy.jar(;;;;;;**.class)] (Duplicate zip entry [org.apache.http.legacy.jar:android/ne
t/http/DelegatingSSLSession.class]))
:app:transformClassesAndResourcesWithProguardForRelease FAILED

网站部署在SD卡访问不了,求大神指点

整个web文件夹复制到/storage/emulated/0/ 下面:
File file = new File(Environment.getExternalStorageDirectory(), "web");
String websiteDirectory = file.getAbsolutePath();
StorageWebsite sn = new StorageWebsite(websiteDirectory);
AndServer andServer = new AndServer.Build()
.port(8080)
.timeout(10 * 1000)
.registerHandler("login", new RequestLoginHandler())
// .registerHandler("download", new RequestFileHandler("Your file path"))
.registerHandler("upload", new RequestUploadHandler())
// .website(new AssetsWebsite(mAssetManager, "web")) //网站部署在assets
.website(sn) //网站部署在外部存储卡
.listener(mListener)
.build();
mServer = andServer.createServer();
一直访问不了,有什么设置我没改到的吗?我只改这里,跑的是Demo的代码.
我加了这些权限:



上传文件时出现 java.lang.NoClassDefFoundError 异常

严老师您好:

今天在测试您的这个库时上传文件怎么都不成功,我使用post方式上传一个图片文件,在sample程序中会出现如下异常:

FATAL EXCEPTION: pool-1-thread-1
                                                                                 Process: com.yanzhenjie.andserver.sample, PID: 26026
                                                                                 java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/commons/io/output/DeferredFileOutputStream;
                                                                                     at org.apache.commons.fileupload.disk.DiskFileItem.getOutputStream(DiskFileItem.java:538)
                                                                                     at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:369)
                                                                                     at com.yanzhenjie.andserver.sample.response.AndServerUploadHandler.processFileUpload(AndServerUploadHandler.java:90)
                                                                                     at com.yanzhenjie.andserver.sample.response.AndServerUploadHandler.handle(AndServerUploadHandler.java:62)
                                                                                     at com.yanzhenjie.andserver.DefaultHttpRequestHandler.handle(DefaultHttpRequestHandler.java:43)
                                                                                     at org.apache.http.protocol.HttpService.doService(HttpService.java:248)
                                                                                     at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:192)
                                                                                     at com.yanzhenjie.andserver.RequestHandleTask.run(RequestHandleTask.java:49)
                                                                                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                     at java.lang.Thread.run(Thread.java:818)
                                                                                  Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.commons.io.output.DeferredFileOutputStream" on path: DexPathList[[zip file "/data/app/com.yanzhenjie.andserver.sample-1/base.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
                                                                                     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                                                     at org.apache.commons.fileupload.disk.DiskFileItem.getOutputStream(DiskFileItem.java:538at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:369at com.yanzhenjie.andserver.sample.response.AndServerUploadHandler.processFileUpload(AndServerUploadHandler.java:90at com.yanzhenjie.andserver.sample.response.AndServerUploadHandler.handle(AndServerUploadHandler.java:62at com.yanzhenjie.andserver.DefaultHttpRequestHandler.handle(DefaultHttpRequestHandler.java:43at org.apache.http.protocol.HttpService.doService(HttpService.java:248at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:192at com.yanzhenjie.andserver.RequestHandleTask.run(RequestHandleTask.java:49at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587at java.lang.Thread.run(Thread.java:818Suppressed: java.lang.ClassNotFoundException: org.apache.commons.io.output.DeferredFileOutputStream
                                                                                     at java.lang.Class.classForName(Native Method)
                                                                                     at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                                                     at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:504)

请问是我传的参数有问题吗?我已经按照您博客中的描述对sample程序添加了 useLibrary 'org.apache.http.legacy',sdk中也不缺失文件,希望您如果看到的话能在百忙中抽出时间不吝赐教

关于使用StorageWebsite时遇到的问题

功能:开启的服务器,通过拍照保存得到的图片,使用ip:8080//storage/emulated/0/path/图片.png查看拍照得到的图片发现<该网站无法运行>,然后重启一次服务器,再打开同样的链接才能查看
请问:是不是不能获取到服务器启动后的新建的文件链接?

AssetsWrapper类里面的getInputStream一直返回是null....

Uploading AFBN}C2@2{HTQXB[LR]3%SO.png…
关于asset层级就是这样的 debug的时候 发现AssetsWrapper里面的scanFile方法会不断循环 由于getInputStream一直返回null吧 debug的时候我修改了getInputStream的文件名参数 改成index.html后就不会无限循环了 读取了14个循环后结束 不过浏览器看也是不正常的
Uploading Y81XZZ{GY5IONZ%MB(LAIET.png…

文件上传错误

java.lang.VerifyError org/apache/commons/fileupload/disk/DiskFileItem
org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:209)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:365)
com.example.shenzg.server.UploadFileHandler.processFileUpload(UploadFileHandler.java:68) com.example.shenzg.server.UploadFileHandler.handle(UploadFileHandler.java:40)
com.yanzhenjie.andserver.DefaultHttpRequestHandler.handle(DefaultHttpRequestHandler.java:43)
org.apache.http.protocol.HttpService.doService(HttpService.java:243) org.apache.http.protocol.HttpService.handleRequest(HttpService.java:187) com.yanzhenjie.andserver.RequestHandleTask.run(RequestHandleTask.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
java.lang.Thread.run(Thread.java:841)

当我使用上传文件功能时报出如下错误。上传文件的功能使用能否给出适当的例子。

关于AssetsManager的引用

sample中CoreService在停止服务后关闭对AseetsManager的引用,重新开始服务后,会导致AssetsWebsite无法获取到assets中的文件。
如果不关闭,重新开始就正常了。
请问这个manager如何处理比较好?

客户端往服务端上传文件返回码500

服务端报错:org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

客户端请求代码:
MediaType imageMediaType = MediaType.parse("multipart/form-data");
File imageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "666.jpg");
RequestBody requestBody = RequestBody.create(imageMediaType, imageFile);
Request request = new Request.Builder().url("http://192.168.1.100:8080/upload").post(requestBody).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@OverRide
public void onFailure(Call call, IOException e) {
Message msg=mhandler.obtainMessage();
msg.what = 0;
msg.obj = "onFailure" + e.toString();
mhandler.sendMessage(msg);
}

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Message msg=mhandler.obtainMessage();
            msg.what = 0;
            msg.obj = "onResponse"+response.toString();
            mhandler.sendMessage(msg);
        }
    });

客户端用的是okhttp,问一下是不是客户端代码有问题?

IP地址有时候会为0.0.0.0

额,严大大就是我使用过程中有时候IP地址会变成0.0.0.0,然而实际的情况并不是这个数值,所以后面我是使用的判断wifi是否开启的广播,然后再开启服务,但是也是会偶尔发生这个问题,请问这个是什么原因呢?不能能否有方法将IP地址变成固定的域名或是固定ip,那个 InetAddress 类好像只能获取,求严大大教导一波!!

提个小bug。

如果 我只需要 registerHandler 的时候 不给 Website 的话, CoreThread----registerRequestHandler方法里面的mWebDirectory 会报空,if (mWebDirectory != null){
mWebDirectory.onRegister(websiteMap);
}

请问实现的RequestHandler为什么不回调??使用您的登录,点击sign in 直接501

========================================
AndServer andServer = new AndServer.Build()
.port(8080)
.timeout(10 * 1000)
.registerHandler("login", new RequestLoginHandler())
// .registerHandler("download", new RequestFileHandler("Your file path"))
.registerHandler("download", new RequestFileHandler(path))
.registerHandler("upload", new RequestUploadHandler())
.website(new AssetsWebsite(mAssetManager, "web"))
.listener(mListener)
.build();

image

index.html
添加

下载

点击下载 501

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.