package org.nanohttpd.protocols.http;
/*
* #%L
* NanoHttpd-Core
* %%
* Copyright (C) 2012 - 2016 nanohttpd
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the nanohttpd nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.regex.Matcher;
import javax.net.ssl.SSLException;
import org.nanohttpd.protocols.http.NanoHTTPD.ResponseException;
import org.nanohttpd.protocols.http.content.ContentType;
import org.nanohttpd.protocols.http.content.CookieHandler;
import org.nanohttpd.protocols.http.request.Method;
import org.nanohttpd.protocols.http.response.Response;
import org.nanohttpd.protocols.http.response.Status;
import org.nanohttpd.protocols.http.tempfiles.ITempFile;
import org.nanohttpd.protocols.http.tempfiles.ITempFileManager;
public class HTTPSession implements IHTTPSession {
public static final String POST_DATA = "postData";
private static final int REQUEST_BUFFER_LEN = 512;
private static final int MEMORY_STORE_LIMIT = 1024;
public static final int BUFSIZE = 8192;
public static final int MAX_HEADER_SIZE = 1024;
private final NanoHTTPD httpd;
private final ITempFileManager tempFileManager;
private final OutputStream outputStream;
private final BufferedInputStream inputStream;
private int splitbyte;
private int rlen;
private String uri;
private Method method;
private Map<String, List<String>> parms;
private Map<String, String> headers;
private CookieHandler cookies;
private String queryParameterString;
private String remoteIp;
private String protocolVersion;
public HTTPSession(NanoHTTPD httpd, ITempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) {
this.httpd = httpd;
this.tempFileManager = tempFileManager;
this.inputStream = new BufferedInputStream(inputStream, HTTPSession.BUFSIZE);
this.outputStream = outputStream;
}
public HTTPSession(NanoHTTPD httpd, ITempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
this.httpd = httpd;
this.tempFileManager = tempFileManager;
this.inputStream = new BufferedInputStream(inputStream, HTTPSession.BUFSIZE);
this.outputStream = outputStream;
this.remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
this.headers = new HashMap<String, String>();
}
/**
* Decodes the sent headers and loads the data into Key/value pairs
*/
private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, List<String>> parms, Map<String, String> headers) throws ResponseException {
try {
// Read the request line
String inLine = in.readLine();
if (inLine == null) {
return;
}
StringTokenizer st = new StringTokenizer(inLine);
if (!st.hasMoreTokens()) {
throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");
}
pre.put("method", st.nextToken());
if (!st.hasMoreTokens()) {
throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");
}
String uri = st.nextToken();
// Decode parameters from the URI
int qmi = uri.indexOf('?');
if (qmi >= 0) {
decodeParms(uri.substring(qmi + 1), parms);
uri = NanoHTTPD.decodePercent(uri.substring(0, qmi));
} else {
uri = NanoHTTPD.decodePercent(uri);
}
// If there's another token, its protocol version,
// followed by HTTP headers.
// NOTE: this now forces header names lower case since they are
// case insensitive and vary by client.
if (st.hasMoreTokens()) {
protocolVersion = st.nextToken();
} else {
protocolVersion = "HTTP/1.1";
NanoHTTPD.LOG.log(Level.FINE, "no protocol version specified, strange. Assuming HTTP/1.1.");
}
String line = in.readLine();
while (line != null && !line.trim().isEmpty()) {
int p = line.indexOf(':');
if (p >= 0) {
headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());
}
line = in.readLine();
}
pre.put("uri", uri);
} catch (IOException ioe) {
throw new ResponseException(Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
/**
* Decodes the Multipart Body data and put it into Key/Value pairs.
*/
private void decodeMultipartFormData(ContentType contentType, ByteBuffer fbuf, Map<String, List<String>> parms, Map<String, String> files) throws ResponseException {
int pcount = 0;
try {
int[] boundaryIdxs = getBoundaryPositions(fbuf, contentType.getBoundary().getBytes());
if (boundaryIdxs.length < 2) {
throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but contains less than two boundary strings.");
}
byte[] partHeaderBuff = new byte[MAX_HEADER_SIZE];
for (int boundaryIdx = 0; boundaryIdx < boundaryIdxs.length - 1; boundaryIdx++) {
fbuf.position(boundaryIdxs[boundaryIdx]);
int len = (fbuf.remaining() < MAX_HEADER_SIZE) ? fbuf.remaining() : MAX_HEADER_SIZE;
fbuf.get(partH
没有合适的资源?快使用搜索试试~ 我知道了~
使用NanoHttpd在Android项目中搭建服务器
共138个文件
xml:63个
java:34个
png:10个
需积分: 46 21 下载量 7 浏览量
2020-07-22
16:28:02
上传
评论
收藏 582KB ZIP 举报
温馨提示
NanoHTTPD是一个免费、轻量级的(只有一个Java文件) HTTP服务器,可以很好地嵌入到Java程序中。支持 GET, POST, PUT, HEAD 和 DELETE 请求,支持文件上传,占用内存很小。
资源推荐
资源详情
资源评论
收起资源包目录
使用NanoHttpd在Android项目中搭建服务器 (138个子文件)
gradlew.bat 2KB
executionHistory.bin 1.12MB
classAnalysis.bin 326KB
fileHashes.bin 150KB
jarAnalysis.bin 136KB
outputFiles.bin 92KB
taskHistory.bin 45KB
resourceHashesCache.bin 19KB
last-build.bin 1B
.gitignore 222B
.gitignore 8B
build.gradle 1KB
build.gradle 593B
settings.gradle 51B
gradlew 5KB
app.iml 13KB
LocationServer.iml 963B
gradle-wrapper.jar 53KB
HTTPSession.java 27KB
NanoHTTPD.java 23KB
Response.java 15KB
MainActivity.java 5KB
GetPhotoFromPhotoAlbum.java 4KB
CookieHandler.java 4KB
ContentType.java 4KB
Status.java 4KB
ClientHandler.java 4KB
FileServer.java 3KB
ServerRunnable.java 3KB
DefaultAsyncRunner.java 3KB
DefaultTempFileManager.java 3KB
IHTTPSession.java 3KB
Cookie.java 3KB
SecureServerSocketFactory.java 3KB
DefaultTempFile.java 3KB
ServerRunner.java 3KB
ChunkedOutputStream.java 3KB
Method.java 2KB
DefaultServerSocketFactory.java 2KB
ITempFile.java 2KB
ITempFileManager.java 2KB
IFactoryThrowing.java 2KB
DefaultTempFileManagerFactory.java 2KB
IHandler.java 2KB
IAsyncRunner.java 2KB
IFactory.java 2KB
IStatus.java 2KB
HttpServer.java 2KB
SharedFile.java 886B
ExampleInstrumentedTest.java 797B
IpUtils.java 775B
ExampleUnitTest.java 404B
buildOutputCleanup.lock 17B
executionHistory.lock 17B
javaCompile.lock 17B
fileContent.lock 17B
fileHashes.lock 17B
ic_launcher_round.png 16KB
ic_launcher_round.png 12KB
ic_launcher.png 10KB
ic_launcher.png 8KB
ic_launcher_round.png 7KB
ic_launcher_round.png 5KB
ic_launcher.png 5KB
ic_launcher.png 4KB
ic_launcher_round.png 3KB
ic_launcher.png 3KB
proguard-rules.pro 772B
gradle.properties 1KB
local.properties 428B
gradle-wrapper.properties 238B
cache.properties 53B
gc.properties 0B
gc.properties 0B
build_file_checksums.ser 539B
workspace.xml 12KB
ic_launcher_background.xml 6KB
Project.xml 3KB
ic_launcher_foreground.xml 2KB
AndroidManifest.xml 1KB
activity_main.xml 1KB
Gradle__com_github_bumptech_glide_gifdecoder_4_10_0_aar.xml 1KB
jarRepositories.xml 1KB
Gradle__androidx_test_espresso_espresso_idling_resource_3_2_0_aar.xml 976B
Gradle__androidx_test_espresso_espresso_core_3_2_0_aar.xml 899B
Gradle__pub_devrel_easypermissions_1_3_0_aar.xml 895B
Gradle__com_github_bumptech_glide_glide_4_10_0_aar.xml 877B
Gradle__androidx_drawerlayout_drawerlayout_1_0_0_aar.xml 872B
Gradle__androidx_appcompat_appcompat_1_1_0_aar.xml 848B
Gradle__androidx_test_ext_junit_1_1_1_aar.xml 846B
Gradle__androidx_fragment_fragment_1_1_0_aar.xml 840B
Gradle__androidx_test_monitor_1_2_0_aar.xml 830B
Gradle__androidx_test_core_1_2_0_aar.xml 827B
Gradle__androidx_test_runner_1_2_0_aar.xml 823B
Gradle__com_github_bumptech_glide_disklrucache_4_10_0_jar.xml 810B
Gradle__androidx_core_core_1_1_0_aar.xml 808B
Gradle__com_github_bumptech_glide_annotations_4_10_0_jar.xml 803B
Gradle__org_hamcrest_hamcrest_integration_1_3_jar.xml 793B
gradle.xml 767B
Gradle__androidx_annotation_annotation_1_1_0_jar.xml 765B
共 138 条
- 1
- 2
资源评论
黄大包
- 粉丝: 43
- 资源: 3
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功