Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

151
LINES

< > BotCompany Repo | #1000407 // Android web server test

JavaX source code (Android) - run with: the app

import android.widget.*;
import android.view.*;
import android.content.Context;
import android.app.Activity;
import java.util.Timer;
import java.util.TimerTask;
import java.io.*;
import java.net.*;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class main {
  private static HttpServer server;
  private static int port = 8080;
  private static String text = "blabla";
  
  static class Lg {
    Activity context;
    ScrollView sv;
    TextView tv;
    StringBuilder buf = new StringBuilder();
    
    Lg(Activity context) {
      this.context = context;
      sv = new ScrollView(context);
      tv = new TextView(context);
      tv.setText(buf.toString());
      sv.addView(tv);
    }
    
    View getView() {
      return sv;
    }
    
    void print(final String s) {
      context.runOnUiThread(new Runnable() {
        public void run() {
          buf.append(s);
          tv.setText(buf.toString());
        }
      });
    }
    
    void println(String s) {
      print(s + "\n");
    }
  }
  
  static Lg lg;
  
  public static View main(final Activity context) {
    lg = new Lg(context);
    
    OutputStream outputStream = new OutputStream() {
      public void write(int b) {
        try {
          lg.print(new String(new byte[] {(byte) b}, "UTF-8")); // This is crap
        } catch (UnsupportedEncodingException e) {}
      }
      
      @Override
      public void write(byte[] b, int off, int len) {
        try {
          lg.print(new String(b, off, len, "UTF-8")); // This is crap
        } catch (UnsupportedEncodingException e) {}
      }
    };
    
    PrintStream ps = new PrintStream(outputStream, true);
    System.setOut(ps);
    System.setErr(ps);
    
    new Thread() {
      public void run() {
        try {
          server = HttpServer.create(new InetSocketAddress(port), 0);
          createHttpContext("/", new MainContext());
          server.setExecutor(null); // creates a default executor
          server.start();
          System.out.println("HTTP server started (listening on port " + port + "!)");
        } catch (Throwable e) {
          e.printStackTrace();
        }
      }
    }.start();

    return lg.getView();
  }

  private static void createHttpContext(String path, HttpHandler handler) {
    server.createContext(path, new SafeHttpHandler(handler));
  }

  public static class SafeHttpHandler implements HttpHandler {
    private HttpHandler handler;

    public SafeHttpHandler(HttpHandler handler) {
      this.handler = handler;
    }

    public void handle(HttpExchange exchange) throws IOException {
      System.out.println("[web server] Handling request: " + exchange.getRequestURI());
      try {
        handler.handle(exchange);
      } catch (Throwable e) {
        String stackTrace = getStackTrace(e);
        sendServerError(exchange, stackTrace);
        System.out.println(stackTrace);
      } finally {
        exchange.close();
        System.out.println("[web server] Done handling request: " + exchange.getRequestURI());
      }
    }
  }

  public static String getStackTrace(Throwable e) {
    StringWriter stringWriter = new StringWriter();
    e.printStackTrace(new PrintWriter(stringWriter));
    return stringWriter.toString();
  }

  public static void sendHtml(HttpExchange exchange, String content) throws IOException {
    int responseCode = 200;
    String contentType = "text/html";
    sendHttpTextResponse(exchange, responseCode, content, contentType);
  }

  public static void sendHttpTextResponse(HttpExchange exchange, int responseCode, String content, String contentType) throws IOException {
    byte[] bytes = content.getBytes("UTF-8");
    String header = contentType + "; charset=utf-8";
    System.out.println("Sending content type: " + header);
    exchange.getResponseHeaders().set("Content-Type", header);
    exchange.sendResponseHeaders(responseCode, bytes.length);
    OutputStream os = exchange.getResponseBody();
    os.write(bytes);
    os.close();
  }

  public static void sendServerError(HttpExchange exchange, String response) throws IOException {
    sendHttpTextResponse(exchange, 500, response, "text/plain");
  }

  public static class MainContext implements HttpHandler {
    public void handle(HttpExchange httpExchange) throws IOException {
      String html = "blabla" + System.currentTimeMillis();
      sendHtml(httpExchange, html);
    }
  }
}

Author comment

Began life as a copy of #1000406

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1000407
Snippet name: Android web server test
Eternal ID of this version: #1000407/1
Text MD5: 6d2e5a9c0d2b048fbe6ed13f46c93302
Author: stefan
Category: javax android
Type: JavaX source code (Android)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-03 03:30:28
Source code size: 4623 bytes / 151 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 755 / 605
Referenced in: [show references]