Android应用中内置Https服务器访问

准备1:必要、非必要的权限

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

准备2:NanoHTTPD的jar包,放入Android Studio项目的libs中,并确保被引用

           地址链接:https://github.com/NanoHttpd/nanohttpd/releases/download/nanohttpd-project-2.2.0/nanohttpd-2.2.0.jar

步骤1:建立一个服务接收类

public class HttpsServer extends NanoHTTPD {

    public HttpsServer (int port) {
        super(port);
    }

    @Override
    public Response serve(IHTTPSession session) {
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html><body>");
        InputStream in= MyServer.class.getResourceAsStream(session.getUri());
        String msg= null;
        String uri= session.getUri();
        if(uri.startsWith("/api")) {
            builder.append("{\"status\": \"success\",\"content\": \"this is from https\"}");
        }else {
            builder.append("Hello from https");
        }
        builder.append("</body></html>\n");
        return newFixedLengthResponse(builder.toString());
    }
}

步骤2:建立一个后台服务

public class HttpService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        HttpServer httpServer = new HttpServer(端口号);
        try {
            //读取证书,注意这里的密码必须设置为证书的密码
            InputStream keystoreStream = getResources().openRawResource(R.raw.serversssl); //签名证书 用Portecle工具中菜单项Change keyStore Type转化为BKS类型 之后放入res的raw文件夹中
            KeyStore keyStore = KeyStore.getInstance("BKS");
            keyStore.load(keystoreStream, null);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, "123456".toCharArray());
            httpServer.makeSecure(NanoHTTPD.makeSSLSocketFactory(keyStore, keyManagerFactory), null);
        }catch (Exception ex){
        }

        try {
            httpServer.start(NanoHTTPD.SOCKET_READ_TIMEOUT, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }
}

步骤3:注册 启动 访问

 //1、注册
<service android:name=".HttpService"
            android:enabled="true"
            android:exported="true"/>

 //2、启动服务
  Intent startIntent = new Intent(this, HttpService.class);
  startService(startIntent);

//3、访问
浏览器地址输入:https://127.0.0.1:端口号 或wifi下IP地址https://IP:端口号   端口号好加/api返回api后面的数据

步骤4:内置WebView访问

//对WebView控件进行一个设置       
        WebView webview = findViewById(R.id.webview);

        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setGeolocationEnabled(true);
        webview.getSettings().setDatabaseEnabled(true);
        //设置定位的数据库路径
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webview.getSettings().setGeolocationDatabasePath(dir);
        webview.getSettings().setGeolocationEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();//这里是关键,直接信任证书,否则页面打不开
                //super.onReceivedSslError(view, handler, error);
            }

        });

        webview.setWebChromeClient(new WebChromeClient());

        webview.loadUrl(getIntent().getStringExtra("url"));//这里加载的是https地址可以写死127.0.0.1,也可以从前个页面获取wifi的ip地址

补充:只访问http不要htpps ,把HttpService中证书那一块try{}中的代码去掉就行了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值