Android Studio 에서 NanoHttpd 테스트 (어플에서 웹서비스 하기)

프로그래밍/Android (Java)|2018. 10. 1. 17:50
반응형

1. bulid.gradle (Module: app)
  dependencies 에 com.nanohttpd:nanohttpd-webserver:2.1.1' 추가
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.nanohttpd:nanohttpd-webserver:2.1.1'
}

2. AndroidManifest.xml 에 퍼미션추가
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

3. activity_main.xml 에 서버 IP 주소를 보여줄 TextView 추가
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.rock.myhttpd.MainActivity">

    <TextView
        android:id="@+id/ipaddr"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="40dp"
        />
    <TextView
        android:id="@+id/hello"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello"
        />
</LinearLayout>

4. MainActivity.java
package com.example.rock.myhttpd;

import fi.iki.elonen.NanoHTTPD;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private WebServer server;
    private static final String TAG = "MYSERVER";
    private static final int PORT = 8080;
    String ipAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView text = (TextView) findViewById(R.id.ipaddr);
        ipAddress = getLocalIpAddress();

        if (ipAddress != null) {
            text.setText("Please Access:" + "http://" + ipAddress + ":" + PORT);
        } else {
            text.setText("Wi-Fi Network Not Available");
        }

        server = new WebServer();
        try {
            server.start();
        } catch(IOException ioe) {
            Log.w("Httpd", "The server could not start.");
        }
        Log.w("Httpd", "Web server initialized.");

    }

    // DON'T FORGET to stop the server
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (server != null)
            server.stop();
    }

    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if(!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        String ipAddr = inetAddress.getHostAddress();
                        return ipAddr;
                    }
                }
            }
        } catch (SocketException ex) {
            Log.d(TAG, ex.toString());
        }
        return null;
    }


    private class WebServer extends NanoHTTPD {

        public WebServer()
        {
            super(PORT);
        }

        @Override
        public Response serve(String uri, Method method,
                              Map<String, String> header,
                              Map<String, String> parameters,
                              Map<String, String> files) {
            String answer = "";
            try {
                // Open file from SD Card
                File root = Environment.getExternalStorageDirectory();
                FileReader index = new FileReader(root.getAbsolutePath() +
                        "/www/index.html");
                BufferedReader reader = new BufferedReader(index);
                String line = "";
                while ((line = reader.readLine()) != null) {
                    answer += line;
                }
                reader.close();

            } catch(IOException ioe) {
                Log.w("Httpd", ioe.toString());
            }


            return new NanoHTTPD.Response(answer);
        }
    }
}

5. 안드로이폰 SD카드에 www 디렉토리생성
- 내파일 > 모든파일 선택 후 www 디렉토리 생성

6. 아래와 같은 샘플 html 을 작성하여 index.html 로 저장하고 www 디렉토리에 복사
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>test</title>
 </head>
 <body>
  <h1>TEST</h1>
  <h2><font color=red>한글은 잘 나옵니까? ^^</font></h2>
 </body>
</html>

7. 앱을 실행시키고(httpd 서버를 가동) PC 에서 웹브라우져로 접속해 본다.



[출처] http://devnote1.blogspot.com/2016/05/android-studio-nanohttpd.html

반응형

댓글()