本文整理汇总了Java中fi.iki.elonen.NanoHTTPD.Response类的典型用法代码示例。如果您正苦于以下问题:Java Response类的具体用法?Java Response怎么用?Java Response使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Response类属于fi.iki.elonen.NanoHTTPD包,在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doGet
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
public Response doGet(IHTTPSession session) {
String uri = session.getUri();
String path = uri.substring(getRequestMappingURL().length());
File result = new File(basePath, path);
String requestCanonicalPath;
try {
requestCanonicalPath = result.getCanonicalPath();
} catch (IOException e1) {
return new503ErrorResponse();
}
//prevent escape from configured base directory
if (!requestCanonicalPath.startsWith(canonicalBasePath) || !result.exists()) {
return NanoHTTPD.newFixedLengthResponse(fi.iki.elonen.NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "not found");
}
try {
return NanoHTTPD.newFixedLengthResponse(fi.iki.elonen.NanoHTTPD.Response.Status.OK, getMimeType(uri), new FileInputStream(result), result.length());
} catch (FileNotFoundException e) {
return new503ErrorResponse();
}
}
示例2: get
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
@Override
public Response get(UriResource uriResource, Map<String, String> urlParams, IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
//Log.d(TAG, "Method: " + method + ", Url: " + uri);
try {
EpubFetcher fetcher = uriResource.initParameter(EpubFetcher.class);
int offset = uri.indexOf("/", 0);
int startIndex = uri.indexOf("/", offset + 1);
String filePath = uri.substring(startIndex + 1);
Link link = fetcher.publication.getResourceMimeType(filePath);
String mimeType = link.getTypeLink();
InputStream inputStream = fetcher.getDataInputStream(filePath);
response = serveResponse(session, inputStream, mimeType);
} catch (EpubFetcherException e) {
e.printStackTrace();
return NanoHTTPD.newFixedLengthResponse(Status.INTERNAL_ERROR, getMimeType(), ResponseStatus.FAILURE_RESPONSE);
}
return response;
}
示例3: serve
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
@Override
public Response serve(IHTTPSession session) {
Response response;
String uri = session.getUri();
if (uri.equals("/")){
uri = "/index.html";
}
String mimetype = getMimeType(uri);
Log.d("HTTPServer","MimeType: "+mimetype);
if (mimetype != null) {
//Handle text files
if (mimetype.contains("text/") || mimetype.contains("image/")){
response = newFixedLengthResponse(getTextFile(uri.substring(1)));
} else { //handle binary files
FileInputStream fcontent = getBinaryFile(uri.substring(1));
response = NanoHTTPD.newChunkedResponse(Response.Status.OK,mimetype,fcontent);
}
response.setMimeType(mimetype);
} else { //Let API Object handle the request
response = newFixedLengthResponse(mAPI.handle(session));
response.setMimeType("application/json");
}
//Allow CORS
response.addHeader("Access-Control-Allow-Origin","*");
response.addHeader("Access-Control-Allow-Headers","auth-user, auth-password");
return response;
}
示例4: handlePolling
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
public Response handlePolling(UUID uuid) {
PeerEntity peer = peerRepository.get(uuid);
if (peer != null) {
// Try to start worker if not already running
peerHive.spawnWorker(peer);
}
BlockingQueue<EventEntity> queue = queueRepository.getOrCreate(uuid);
try {
EventEntity event = queue.poll(REQUEST_TIMEOUT, TimeUnit.SECONDS);
if (event != null) {
Log.d("RequestHandler", "Handling event " + event.getEvent());
return sendEvent(event);
} else {
return sendTimeout();
}
} catch (InterruptedException e) {
return sendServerError("SERVER INTERNAL ERROR: InterruptedException: " + e.getMessage());
}
}
示例5: doGet
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
@Override
public void doGet(IHTTPSession session, Response response) {
if (!webServer.getUser().isAdmin()) {
response.setStatus(Response.Status.FORBIDDEN);
return;
}
response.setMimeType("application/json");
String pkname = session.getParms().get("id");
if (StringUtils.isNotBlank(pkname)) {
User user = PersistenceManager.getDao(User.class).findOne(Long.valueOf(pkname));
if (user != null) {
response.setData(VntUtil.getInputStream(VntUtil.toJson(user)));
}
} else {
response.setData(VntUtil.getInputStream(VntUtil.toJson(PersistenceManager.getDao(User.class).findAll())));
}
}
示例6: doGet
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
@Override
public void doGet(IHTTPSession session, Response response) {
String torrentString = null;
try {
torrentString = URLDecoder.decode(session.getParms().get("torrent"), "UTF-8");
torrentString = session.getParms().get("torrent");
log.info(torrentString);
}
catch (UnsupportedEncodingException e) {
log.error("Error decoding torrent param", e);
}
Torrent torrent = VntUtil.fromJson(torrentString, Torrent.class);
InputStream inputStream = null;
if (torrent != null) {
TrackerManager trackerManager = TrackerManagerFactory.getInstance(torrent.getTracker());
trackerManager.setUser(torrent.getUsername(), torrent.getPassword());
inputStream = trackerManager.download(torrent);
response.addHeader("Content-Disposition", "attachment; filename=\"" + torrent.getName() + ".torrent\"");
response.setMimeType("application/octet-stream; charset=UTF-8");
response.setChunkedTransfer(true);
}
response.setData(inputStream);
}
示例7: doGet
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
@Override
public void doGet(IHTTPSession session, Response response) {
Boolean close = Boolean.valueOf(session.getParms().get("c"));
String seedbox = session.getParms().get("seedbox");
Torrent torrent = VntUtil.fromJson(session.getParms().get("torrent"), Torrent.class);
if (StringUtils.isNotBlank(seedbox) && torrent != null) {
TrackerManager trackerManager = TrackerManagerFactory.getInstance(torrent.getTracker());
trackerManager.setUser(torrent.getUsername(), torrent.getPassword());
Seedbox seedboxConfig = PersistenceManager.getDao(Seedbox.class).findOne(Long.valueOf(seedbox));
Wicker wicker = new WickerFactory(seedboxConfig.getWebClient().getSimpleName()).newInstance(seedboxConfig.getUrl(), seedboxConfig.getUsername(), seedboxConfig.getPassword());
wicker.uploadTorrent(trackerManager.download(torrent), seedboxConfig.getLabel());
}
if (close) {
response.setData(VntUtil.getInputStream("<script type='text/javascript'>alert('Torrent sent with success.');window.close();</script>"));
} else {
response.setMimeType("application/json; charset=UTF-8");
ReturnObject returnObject = new ReturnObject(true, null);
response.setData(VntUtil.getInputStream(VntUtil.toJson(returnObject)));
}
}
示例8: doGet
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
@Override
public void doGet(IHTTPSession session, Response response) {
response.setMimeType("application/json");
String id = session.getParms().get("id");
boolean count = Boolean.valueOf(session.getParms().get("count"));
if (count) {
response.setData(VntUtil.getInputStream(VntUtil.toJson(new ReturnObject(true, webServer.getUser().getJobs().size()))));
} else if (StringUtils.isNotBlank(id)) {
Job job = PersistenceManager.getDao(Job.class).findOne(Long.valueOf(id));
if (job != null) {
response.setData(VntUtil.getInputStream(VntUtil.toJson(job)));
}
} else {
response.setData(VntUtil.getInputStream(VntUtil.toJson(webServer.getUser().getJobs())));
}
}
示例9: doGet
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
@Override
public void doGet(IHTTPSession session, Response response) {
ReturnObject returnObject = null;
Torrent torrent = VntUtil.fromJson(session.getParms().get("torrent"), Torrent.class);
if (torrent != null) {
if (!torrent.isDetailed()) {
TrackerManager trackerManager = TrackerManagerFactory.getInstance(torrent.getTracker());
trackerManager.setUser(torrent.getUsername(), torrent.getPassword());
try {
trackerManager.getDetails(torrent);
returnObject = new ReturnObject(true, torrent);
} catch (VntException e) {
returnObject = new ReturnObject(false, "Error when trying to get details", e.getStackTrace());
}
}
response.setMimeType("application/json");
response.setData(VntUtil.getInputStream(VntUtil.toJson(returnObject)));
}
}
示例10: doGet
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
@Override
public void doGet(IHTTPSession session, Response response) {
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
String url = session.getParms().get("image");
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0.3");
httpGet.addHeader("Accept-Encoding", "gzip");
CloseableHttpResponse imdbResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = imdbResponse.getEntity();
response.setChunkedTransfer(true);
response.setMimeType("image/jpeg");
response.setData(httpEntity.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
示例11: testUnloadQueue
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
@Test
public void testUnloadQueue() throws IOException {
StringBuilder requestBuilder = new StringBuilder();
requestBuilder.append("GET " + HttpServerTest.URI + " HTTP/1.1").append(System.getProperty("line.separator")).append("Cookie: theme=light; sessionToken=abc123");
ByteArrayInputStream inputStream = new ByteArrayInputStream(requestBuilder.toString().getBytes());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
NanoHTTPD.HTTPSession session = this.testServer.createSession(this.tempFileManager, inputStream, outputStream);
session.execute();
CookieHandler cookieHandler = session.getCookies();
Response response = NanoHTTPD.newFixedLengthResponse("");
cookieHandler.set("name", "value", 30);
cookieHandler.unloadQueue(response);
String setCookieHeader = response.getHeader("Set-Cookie");
assertTrue("unloadQueue did not set the cookies correctly", setCookieHeader.startsWith("name=value; expires="));
}
示例12: testDelete
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
@Test
public void testDelete() throws IOException, ParseException {
StringBuilder requestBuilder = new StringBuilder();
requestBuilder.append("GET " + HttpServerTest.URI + " HTTP/1.1").append(System.getProperty("line.separator")).append("Cookie: theme=light; sessionToken=abc123");
ByteArrayInputStream inputStream = new ByteArrayInputStream(requestBuilder.toString().getBytes());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
NanoHTTPD.HTTPSession session = this.testServer.createSession(this.tempFileManager, inputStream, outputStream);
session.execute();
CookieHandler cookieHandler = session.getCookies();
Response response = NanoHTTPD.newFixedLengthResponse("");
cookieHandler.delete("name");
cookieHandler.unloadQueue(response);
String setCookieHeader = response.getHeader("Set-Cookie");
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateString = setCookieHeader.split(";")[1].split("=")[1].trim();
Date date = dateFormat.parse(dateString);
assertTrue("Deleted cookie's expiry time should be a time in the past", date.compareTo(new Date()) < 0);
}
示例13: testNormalDownlaod
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
public void testNormalDownlaod() throws Exception {
Response res = new Response(Response.Status.OK, "text/plain", "ok");
String testPath = "/a";
webServer.urlToDataMap.put(testPath, res);
webServer.start();
Intent i = new Intent();
i.putExtra("url", TEST_SERVER_URI + testPath);
i.putExtra("receiver", resultReceiver);
i.putExtra("destination", dummyFile.getAbsolutePath());
this.startService(i);
synchronized (this) {
// we only wait for 10 seconds to finish this task.
this.wait(10 * 1000);
}
this.shutdownService();
assertEquals(DownloadService.DOWNLOAD_COMPLETE, returnedResultCode);
assertEquals("ok", StringUtils.readAll(dummyFile));
webServer.urlToDataMap.clear();
webServer.stop();
}
示例14: testWrongDestinationDownlaod
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
public void testWrongDestinationDownlaod() throws Exception {
Response res = new Response(Response.Status.OK, "text/plain", "ok");
String testPath = "/a";
webServer.urlToDataMap.put(testPath, res);
webServer.start();
Intent i = new Intent();
i.putExtra("url", TEST_SERVER_URI + testPath);
i.putExtra("receiver", resultReceiver);
i.putExtra("destination", "/wrong destination");
this.startService(i);
synchronized (this) {
// we only wait for 10 seconds to finish this task.
this.wait(10 * 1000);
}
this.shutdownService();
assertEquals(DownloadService.INTERNAL_ERROR, returnedResultCode);
webServer.urlToDataMap.clear();
webServer.stop();
}
示例15: serveMessages
import fi.iki.elonen.NanoHTTPD.Response; //导入依赖的package包/类
private Response serveMessages(long id) {
Log.d(TAG, "Serving messages for " + id);
List<Message> messagesList = SMSUtils.getMessageForThread(id, 20, 0, context);
JSONArray messageArray = new JSONArray();
for (Message m : messagesList) {
JSONObject obj = null;
try {
obj = m.toJSON();
} catch (JSONException e) {
Log.e(TAG, "Unable to serialize JSON for " + m);
}
messageArray.put(obj);
}
String msg = messageArray.toString();
Response response = new Response(msg);
response.setMimeType("application/json");
return response;
}