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

1  
import android.widget.*;
2  
import android.view.*;
3  
import android.content.Context;
4  
import android.app.Activity;
5  
import java.util.Timer;
6  
import java.util.TimerTask;
7  
import java.io.*;
8  
import java.net.*;
9  
10  
import com.sun.net.httpserver.HttpExchange;
11  
import com.sun.net.httpserver.HttpHandler;
12  
import com.sun.net.httpserver.HttpServer;
13  
14  
public class main {
15  
  private static HttpServer server;
16  
  private static int port = 8080;
17  
  private static String text = "blabla";
18  
  
19  
  static class Lg {
20  
    Activity context;
21  
    ScrollView sv;
22  
    TextView tv;
23  
    StringBuilder buf = new StringBuilder();
24  
    
25  
    Lg(Activity context) {
26  
      this.context = context;
27  
      sv = new ScrollView(context);
28  
      tv = new TextView(context);
29  
      tv.setText(buf.toString());
30  
      sv.addView(tv);
31  
    }
32  
    
33  
    View getView() {
34  
      return sv;
35  
    }
36  
    
37  
    void print(final String s) {
38  
      context.runOnUiThread(new Runnable() {
39  
        public void run() {
40  
          buf.append(s);
41  
          tv.setText(buf.toString());
42  
        }
43  
      });
44  
    }
45  
    
46  
    void println(String s) {
47  
      print(s + "\n");
48  
    }
49  
  }
50  
  
51  
  static Lg lg;
52  
  
53  
  public static View main(final Activity context) {
54  
    lg = new Lg(context);
55  
    
56  
    OutputStream outputStream = new OutputStream() {
57  
      public void write(int b) {
58  
        try {
59  
          lg.print(new String(new byte[] {(byte) b}, "UTF-8")); // This is crap
60  
        } catch (UnsupportedEncodingException e) {}
61  
      }
62  
      
63  
      @Override
64  
      public void write(byte[] b, int off, int len) {
65  
        try {
66  
          lg.print(new String(b, off, len, "UTF-8")); // This is crap
67  
        } catch (UnsupportedEncodingException e) {}
68  
      }
69  
    };
70  
    
71  
    PrintStream ps = new PrintStream(outputStream, true);
72  
    System.setOut(ps);
73  
    System.setErr(ps);
74  
    
75  
    new Thread() {
76  
      public void run() {
77  
        try {
78  
          server = HttpServer.create(new InetSocketAddress(port), 0);
79  
          createHttpContext("/", new MainContext());
80  
          server.setExecutor(null); // creates a default executor
81  
          server.start();
82  
          System.out.println("HTTP server started (listening on port " + port + "!)");
83  
        } catch (Throwable e) {
84  
          e.printStackTrace();
85  
        }
86  
      }
87  
    }.start();
88  
89  
    return lg.getView();
90  
  }
91  
92  
  private static void createHttpContext(String path, HttpHandler handler) {
93  
    server.createContext(path, new SafeHttpHandler(handler));
94  
  }
95  
96  
  public static class SafeHttpHandler implements HttpHandler {
97  
    private HttpHandler handler;
98  
99  
    public SafeHttpHandler(HttpHandler handler) {
100  
      this.handler = handler;
101  
    }
102  
103  
    public void handle(HttpExchange exchange) throws IOException {
104  
      System.out.println("[web server] Handling request: " + exchange.getRequestURI());
105  
      try {
106  
        handler.handle(exchange);
107  
      } catch (Throwable e) {
108  
        String stackTrace = getStackTrace(e);
109  
        sendServerError(exchange, stackTrace);
110  
        System.out.println(stackTrace);
111  
      } finally {
112  
        exchange.close();
113  
        System.out.println("[web server] Done handling request: " + exchange.getRequestURI());
114  
      }
115  
    }
116  
  }
117  
118  
  public static String getStackTrace(Throwable e) {
119  
    StringWriter stringWriter = new StringWriter();
120  
    e.printStackTrace(new PrintWriter(stringWriter));
121  
    return stringWriter.toString();
122  
  }
123  
124  
  public static void sendHtml(HttpExchange exchange, String content) throws IOException {
125  
    int responseCode = 200;
126  
    String contentType = "text/html";
127  
    sendHttpTextResponse(exchange, responseCode, content, contentType);
128  
  }
129  
130  
  public static void sendHttpTextResponse(HttpExchange exchange, int responseCode, String content, String contentType) throws IOException {
131  
    byte[] bytes = content.getBytes("UTF-8");
132  
    String header = contentType + "; charset=utf-8";
133  
    System.out.println("Sending content type: " + header);
134  
    exchange.getResponseHeaders().set("Content-Type", header);
135  
    exchange.sendResponseHeaders(responseCode, bytes.length);
136  
    OutputStream os = exchange.getResponseBody();
137  
    os.write(bytes);
138  
    os.close();
139  
  }
140  
141  
  public static void sendServerError(HttpExchange exchange, String response) throws IOException {
142  
    sendHttpTextResponse(exchange, 500, response, "text/plain");
143  
  }
144  
145  
  public static class MainContext implements HttpHandler {
146  
    public void handle(HttpExchange httpExchange) throws IOException {
147  
      String html = "blabla" + System.currentTimeMillis();
148  
      sendHtml(httpExchange, html);
149  
    }
150  
  }
151  
}

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: 756 / 606
Referenced in: [show references]