fi.iki.elonen.NanoHTTPD Java Examples
The following examples show how to use
fi.iki.elonen.NanoHTTPD.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebDriverProxyTest.java From marathonv5 with Apache License 2.0 | 6 votes |
@BeforeClass public void startServer() throws IOException { System.out.println("WebDriverProxyTest.startServer()"); serverPort = findPort(); server = new NanoHTTPD(serverPort) { @Override public Response serve(IHTTPSession session) { try { String data = IOUtils.toString(WebDriverProxyTest.class.getResourceAsStream("form.html"), Charset.defaultCharset()); return newFixedLengthResponse(data); } catch (IOException e) { return super.serve(session); } } }; server.start(); }
Example #2
Source File: FileRequestProcesser.java From TVRemoteIME with GNU General Public License v2.0 | 6 votes |
@Override public boolean isRequest(NanoHTTPD.IHTTPSession session, String fileName) { if(session.getMethod() == NanoHTTPD.Method.GET){ return fileName.startsWith("/file/dir/") || fileName.startsWith("/file/download/"); } else if(session.getMethod() == NanoHTTPD.Method.POST){ switch (fileName) { case "/file/copy": case "/file/cut": case "/file/delete": case "/file/upload": return true; } } return false; }
Example #3
Source File: DConnectWebServerNanoHttpd.java From DeviceConnect-Android with MIT License | 6 votes |
/** * 指定された URI の静的ファイルを返却します. * * @param headers リクエストヘッダー * @param session リクエストのセッション * @param uri リクエストURI * @return レスポンス */ private Response respond(final Map<String, String> headers, final IHTTPSession session, final String uri) { Response r; if (mCors != null && Method.OPTIONS.equals(session.getMethod())) { // クロスドメイン対応としてOPTIONSがきたらDevice Connect で対応しているメソッドを返す // Device Connect 対応外のメソッドだがエラーにはしないのでここで処理を終了。 r = newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT, ""); r.addHeader("Access-Control-Allow-Methods", "GET"); } else if (Method.GET.equals(session.getMethod())) { r = defaultRespond(headers, session, uri); } else { r = newMethodNotAllowedResponse(); } if (mCors != null) { r = addCORSHeaders(headers, r, mCors); } return r; }
Example #4
Source File: MobileApiVersionTest.java From mobile-messaging-sdk-android with Apache License 2.0 | 6 votes |
@Test public void create_success() throws Exception { debugServer.respondWith(NanoHTTPD.Response.Status.OK, DefaultApiClient.JSON_SERIALIZER.serialize(new LatestReleaseResponse("GCM", "3.2.1", "www"))); LatestReleaseResponse response = mobileApiVersion.getLatestRelease(); //inspect http context assertEquals("/mobile/3/version", debugServer.getUri()); assertEquals(1, debugServer.getRequestCount()); assertEquals(NanoHTTPD.Method.GET, debugServer.getRequestMethod()); assertEquals("App my_API_key", debugServer.getHeader("Authorization")); assertNull(debugServer.getBody()); //inspect response assertEquals("GCM", response.getPlatformType()); assertEquals("3.2.1", response.getLibraryVersion()); assertEquals("www", response.getUpdateUrl()); }
Example #5
Source File: RouterNanoHTTPD.java From UIAutomatorWD with MIT License | 6 votes |
public Response get(UriResource uriResource, Map<String, String> urlParams, IHTTPSession session) { StringBuilder text = new StringBuilder("<html><body>"); text.append("<h1>Url: "); text.append(session.getUri()); text.append("</h1><br>"); Map<String, String> queryParams = session.getParms(); if (queryParams.size() > 0) { for (Map.Entry<String, String> entry : queryParams.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); text.append("<p>Param '"); text.append(key); text.append("' = "); text.append(value); text.append("</p>"); } } else { text.append("<p>no params in url</p><br>"); } return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), text.toString()); }
Example #6
Source File: ServerRunner.java From CameraV with GNU General Public License v3.0 | 6 votes |
public static void executeInstance(NanoHTTPD server) { try { server.start(); } catch (IOException ioe) { System.err.println("Couldn't start server:\n" + ioe); System.exit(-1); } System.out.println("Server started, Hit Enter to stop.\n"); try { System.in.read(); } catch (Throwable ignored) { } server.stop(); System.out.println("Server stopped.\n"); }
Example #7
Source File: ServerRunner.java From CameraV with GNU General Public License v3.0 | 6 votes |
public static void executeInstance(NanoHTTPD server) { try { server.start(); } catch (IOException ioe) { System.err.println("Couldn't start server:\n" + ioe); System.exit(-1); } System.out.println("Server started, Hit Enter to stop.\n"); try { System.in.read(); } catch (Throwable ignored) { } server.stop(); System.out.println("Server stopped.\n"); }
Example #8
Source File: TestParameterTamperUnitTest.java From zap-extensions with Apache License 2.0 | 6 votes |
@Test public void shouldContinueScanningIfFirstResponseIsOK() throws Exception { // Given nano.addHandler( new NanoServerHandler("/") { @Override protected Response serve(IHTTPSession session) { return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, ""); } }); rule.init(getHttpMessage("/?p=v"), parent); // When rule.scan(); // Then assertThat(httpMessagesSent, hasSize(greaterThan(1))); assertThat(alertsRaised, hasSize(0)); }
Example #9
Source File: ElementController.java From UIAutomatorWD with MIT License | 6 votes |
@Override public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { String sessionId = urlParams.get("sessionId"); String elementId = urlParams.get("elementId"); try { Element el = Elements.getGlobal().getElement(elementId); JSONObject props = new JSONObject(); props.put("text", el.element.getText()); props.put("description", el.element.getContentDescription()); props.put("enabled", el.element.isEnabled()); props.put("checkable", el.element.isCheckable()); props.put("checked", el.element.isChecked()); props.put("clickable", el.element.isClickable()); props.put("focusable", el.element.isFocusable()); props.put("focused", el.element.isFocused()); props.put("longClickable", el.element.isLongClickable()); props.put("scrollable", el.element.isScrollable()); props.put("selected", el.element.isSelected()); return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(props, sessionId).toString()); } catch (final Exception e) { return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString()); } }
Example #10
Source File: ServerRunner.java From VBrowser-Android with GNU General Public License v2.0 | 6 votes |
public static void executeInstance(NanoHTTPD server) { try { server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); } catch (IOException ioe) { System.err.println("Couldn't start server:\n" + ioe); System.exit(-1); } System.out.println("Server started, Hit Enter to stop.\n"); try { System.in.read(); } catch (Throwable ignored) { } server.stop(); System.out.println("Server stopped.\n"); }
Example #11
Source File: ElementController.java From UIAutomatorWD with MIT License | 6 votes |
@Override public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { String sessionId = urlParams.get("sessionId"); String elementId = urlParams.get("elementId"); try { Element el = Elements.getGlobal().getElement(elementId); final Rect rect = el.element.getVisibleBounds(); JSONObject res = new JSONObject(); res.put("x", rect.left); res.put("y", rect.top); res.put("height", rect.height()); res.put("width", rect.width()); return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(res, sessionId).toString()); } catch (final Exception e) { return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString()); } }
Example #12
Source File: DefaultApiClientTest.java From mobile-messaging-sdk-android with Apache License 2.0 | 6 votes |
@Test public void execute_withQueryParams_withHeaders_withBody_receivesOK() throws Exception { debugServer.respondWith(NanoHTTPD.Response.Status.OK, DefaultApiClient.JSON_SERIALIZER.serialize(new SomeApiResponse(11))); SomeApiResponse result = apiClient.execute(HttpMethod.POST, "http://127.0.0.1:" + debugServer.getListeningPort(), null, null, MapUtils.map("applicationId", "xyz", "currentRegistrationId", "1234"), MapUtils.map("X-Test-1", "test1", "X-Test-2", "test2"), new SomeApiRequest("Test"), SomeApiResponse.class); Assert.assertEquals(11, result.getInternalRegistrationId()); Assert.assertEquals(1, debugServer.getRequestCount()); Assert.assertEquals(NanoHTTPD.Method.POST, debugServer.getRequestMethod()); Assert.assertEquals("/", debugServer.getUri()); Assert.assertEquals("xyz", debugServer.getQueryParameter("applicationId")); Assert.assertEquals("1234", debugServer.getQueryParameter("currentRegistrationId")); Assert.assertNull(debugServer.getQueryParameter("oldRegistrationId")); Assert.assertEquals("{\"name\":\"Test\"}", debugServer.getBody()); Assert.assertEquals("test1", debugServer.getHeader("X-Test-1")); Assert.assertEquals("test2", debugServer.getHeader("X-Test-2")); }
Example #13
Source File: MobileMessagingBaseTestCase.java From mobile-messaging-sdk-android with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { context = getInstrumentation().getContext(); contextMock = mockContext(context); debugServer = new DebugServer(); debugServer.respondWith(NanoHTTPD.Response.Status.BAD_REQUEST, "{\n" + " \"code\": \"500\",\n" + " \"message\": \"Internal server error\"\n" + "}"); debugServer.start(); }
Example #14
Source File: AssetsWeb.java From MyBookshelf with GNU General Public License v3.0 | 5 votes |
public NanoHTTPD.Response getResponse(String path) throws IOException { path = (rootPath + path).replaceAll("/+", File.separator); InputStream inputStream = assetManager.open(path); return NanoHTTPD.newChunkedResponse(NanoHTTPD.Response.Status.OK, getMimeType(path), inputStream); }
Example #15
Source File: TestPathTraversalUnitTest.java From zap-extensions with Apache License 2.0 | 5 votes |
@Override protected Response serve(IHTTPSession session) { String value = getFirstParamValue(session, param); if (ArrayUtils.contains(existingFiles, value)) { return newFixedLengthResponse( Response.Status.OK, NanoHTTPD.MIME_HTML, "File Found"); } return newFixedLengthResponse( Response.Status.NOT_FOUND, NanoHTTPD.MIME_HTML, "404 Not Found"); }
Example #16
Source File: OtherPostRequestProcesser.java From TVRemoteIME with GNU General Public License v2.0 | 5 votes |
@Override public NanoHTTPD.Response doResponse(NanoHTTPD.IHTTPSession session, String fileName, Map<String, String> params, Map<String, String> files) { switch (fileName) { case "/clearCache": RemoteServerFileManager.clearAllFiles(); return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.OK,"ok"); default: return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.NOT_FOUND, "Error 404, file not found."); } }
Example #17
Source File: LocalHTTPD.java From fdroidclient with GNU General Public License v3.0 | 5 votes |
private void enableHTTPS() { try { LocalRepoKeyStore localRepoKeyStore = LocalRepoKeyStore.get(context.get()); SSLServerSocketFactory factory = NanoHTTPD.makeSSLSocketFactory( localRepoKeyStore.getKeyStore(), localRepoKeyStore.getKeyManagers()); makeSecure(factory, null); } catch (LocalRepoKeyStore.InitException | IOException e) { e.printStackTrace(); } }
Example #18
Source File: PlayRequestProcesser.java From TVRemoteIME with GNU General Public License v2.0 | 5 votes |
@Override public boolean isRequest(NanoHTTPD.IHTTPSession session, String fileName) { if(session.getMethod() == NanoHTTPD.Method.POST){ switch (fileName) { case "/play": case "/playStop": case "/changePlayFFI": return true; } } return false; }
Example #19
Source File: MobileApiAppInstanceTest.java From mobile-messaging-sdk-android with Apache License 2.0 | 5 votes |
@Test public void patch_instance_success_examineResponse() throws Exception { debugServer.respondWith(NanoHTTPD.Response.Status.OK, null); mobileApiAppInstance.patchInstance(regId, new HashMap<String, Object>()); //inspect http context assertEquals("/mobile/1/appinstance/1234regId567", debugServer.getUri()); assertEquals(1, debugServer.getRequestCount()); assertEquals(NanoHTTPD.Method.POST, debugServer.getRequestMethod()); assertEquals(HttpMethod.PATCH.name(), debugServer.getHeader("X-HTTP-Method-Override")); assertEquals("App my_API_key", debugServer.getHeader("Authorization")); assertEquals(0, debugServer.getQueryParametersCount()); }
Example #20
Source File: PhonkHttpServer.java From PHONK with GNU General Public License v3.0 | 5 votes |
private Response serveWebIDE(IHTTPSession session) { Response res = null; String uri = session.getUri(); // Clean up uri uri = uri.trim().replace(File.separatorChar, '/'); if (uri.indexOf('?') >= 0) uri = uri.substring(0, uri.indexOf('?')); if (uri.length() == 1) uri = "index.html"; // We never want to request just the '/' if (uri.charAt(0) == '/') uri = uri.substring(1); // using assets, so we can't have leading '/' String mime = getMimeType(uri); // Get MIME type // Read file and return it, otherwise NOT_FOUND is returned AssetManager am = mContext.get().getAssets(); try { // MLog.d(TAG, WEBAPP_DIR + uri); InputStream fi = am.open(WEBAPP_DIR + uri); res = newFixedLengthResponse(Response.Status.OK, mime, fi, fi.available()); } catch (IOException e) { e.printStackTrace(); // MLog.d(TAG, e.getStackTrace().toString()); NanoHTTPD.newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_TYPES.get("txt"), "ERROR: " + e.getMessage()); } return res; //NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), inp, fontSize); }
Example #21
Source File: WebServer.java From haven with GNU General Public License v3.0 | 5 votes |
public WebServer(Context context, String password) throws IOException { super(LOCAL_HOST, LOCAL_PORT); mContext = context; mPassword = password; if (!TextUtils.isEmpty(mPassword)) //require a password to start the server start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); else throw new IOException ("Web password must not be null"); }
Example #22
Source File: VideoServer.java From Android with Apache License 2.0 | 5 votes |
public Response responseVideoStream(IHTTPSession session) { try { FileInputStream fis = new FileInputStream(mVideoFilePath); return new NanoHTTPD.Response(Status.OK, "video/mp4", fis); } catch (FileNotFoundException e) { e.printStackTrace(); return response404(session,mVideoFilePath); } }
Example #23
Source File: WebServer.java From Inspeckage with Apache License 2.0 | 5 votes |
public Response queryProvider(String uri) { Intent intent = new Intent("mobi.acpm.inspeckage.INSPECKAGE_FILTER"); intent.putExtra("package", mPrefs.getString(Config.SP_PACKAGE, "")); intent.putExtra("action", "query"); intent.putExtra("uri", uri); mContext.sendBroadcast(intent, null); return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, "OK"); }
Example #24
Source File: DefaultApiClientTest.java From mobile-messaging-sdk-android with Apache License 2.0 | 5 votes |
@Test(expected = ApiException.class) public void execute_withQueryParams_noHeaders_withBody_receivesError() throws Exception { debugServer.respondWith(NanoHTTPD.Response.Status.UNAUTHORIZED, DefaultApiClient.JSON_SERIALIZER.serialize(new ApiResponse( new ApiError(new ApiServiceException("1", "Invalid Application ID"))))); apiClient.execute(HttpMethod.POST, "http://127.0.0.1:" + debugServer.getListeningPort(), null, null, MapUtils.map("applicationId", "xyz", "currentRegistrationId", "1234"), null, new SomeApiRequest("Test"), ApiResponse.class); }
Example #25
Source File: StreamingWorkbookTest.java From excel-streaming-reader with Apache License 2.0 | 5 votes |
public static void withServer(Consumer<IHTTPSession> onRequest, Runnable func) { try(ExploitServer server = new ExploitServer(onRequest)) { server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); func.run(); } catch(IOException e) { throw new UncheckedIOException(e); } }
Example #26
Source File: AgentStatusHttpdTest.java From gocd with Apache License 2.0 | 5 votes |
@Test void shouldReturnNotFoundForBadUrl() throws Exception { when(session.getMethod()).thenReturn(NanoHTTPD.Method.GET); when(session.getUri()).thenReturn("/foo"); NanoHTTPD.Response response = this.agentStatusHttpd.serve(session); assertThat(response.getStatus()).isEqualTo(NanoHTTPD.Response.Status.NOT_FOUND); assertThat(response.getMimeType()).isEqualTo("text/plain; charset=utf-8"); assertThat(IOUtils.toString(response.getData(), StandardCharsets.UTF_8)).isEqualTo("The page you requested was not found"); }
Example #27
Source File: DConnectServerNanoHttpd.java From DeviceConnect-Android with MIT License | 5 votes |
@Override public void clear() { for (NanoHTTPD.TempFile file : mTempFiles) { try { file.delete(); } catch (Exception ignored) { ignored.printStackTrace(); } } mTempFiles.clear(); }
Example #28
Source File: WebServer.java From USBHIDTerminal with Apache License 2.0 | 5 votes |
@Override public Response serve(IHTTPSession session) { String mimeType = NanoHTTPD.MIME_HTML; String uri = session.getUri(); Response response = new Response("Sample"); if (uri.equals("/websocket")) { response = responseHandler.serve(session); } else { switch (uri) { case "/": uri = "/index.html"; break; } if (uri.endsWith(".js")) { mimeType = MIME_JAVASCRIPT; } else if (uri.endsWith(".css")) { mimeType = MIME_CSS; } else if (uri.endsWith(".html")) { mimeType = MIME_HTML; } else if (uri.endsWith(".jpeg")) { mimeType = MIME_JPEG; } else if (uri.endsWith(".png")) { mimeType = MIME_PNG; } else if (uri.endsWith(".jpg")) { mimeType = MIME_JPEG; } else if (uri.endsWith(".svg")) { mimeType = MIME_SVG; } else if (uri.endsWith(".json")) { mimeType = MIME_JSON; } response.setMimeType(mimeType); response.setData(openPage(uri)); } return response; }
Example #29
Source File: MBTilesServer.java From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public Response serve(IHTTPSession session) { NanoHTTPD.Response response; Method method = session.getMethod(); String uri = session.getUri(); Log.d(TAG, method + " '" + uri + "' "); Matcher matcher = TILE_PATTERN.matcher(uri); if(!matcher.find()) { response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Not found"); } else { String layerName = matcher.group(1); int z = Integer.parseInt(matcher.group(2)); int x = Integer.parseInt(matcher.group(3)); int y = Integer.parseInt(matcher.group(4)); MBTiles mbTiles = layers.get(layerName); if (mbTiles != null) { try { byte[] tile = mbTiles.getTile(z, x, y); if (tile != null) { response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, "image/png", new ByteArrayInputStream(tile)); } else { response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Tile not found"); } } catch(Exception ex) { Log.e(TAG, ex.toString()); response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, ex.toString()); } } else { response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Layer not found"); } } return response; }
Example #30
Source File: TestPathTraversalUnitTest.java From zap-extensions with Apache License 2.0 | 5 votes |
@Override protected Response serve(IHTTPSession session) { String value = getFirstParamValue(session, param); if (attack.equals(value)) { return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, getDirs()); } return newFixedLengthResponse( Response.Status.NOT_FOUND, NanoHTTPD.MIME_HTML, "404 Not Found"); }