Last active
April 23, 2019 14:52
-
-
Save xiejianchao/26321019849d5e88effcc2eda1b27503 to your computer and use it in GitHub Desktop.
Create Http Server In Android Using Nanohttpd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.httpserver; | |
import android.content.Context; | |
import android.support.annotation.NonNull; | |
import android.util.Log; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.Map; | |
import fi.iki.elonen.NanoHTTPD; | |
public class Server extends NanoHTTPD { | |
private static final String TAG = Server.class.getSimpleName(); | |
private Context mContext; | |
private static final String REQUEST_ROOT = "/"; | |
public Server(Context context) { | |
super(8080); | |
this.mContext = context; | |
} | |
@Override | |
public Response serve(IHTTPSession session) { | |
String msg = "<html><body><h1>Hello server</h1>\n"; | |
Map<String, String> parms = session.getParms(); | |
String img = "<img src=\"//cdn2.jianshu" + | |
".io/assets/web/web-note-ad-1-c2e1746859dbf03abe49248893c9bea4.png\" alt=\"Web note " + | |
"ad 1\" />"; | |
if (parms.get("username") == null) { | |
msg += "<form action='?' method='get'>\n <p>Your name: <input type='text' " + | |
"name='username'> " + img + " </p>\n" + "</form>\n"; | |
} else { | |
msg += "<p>Hello, " + parms.get("username") + "!</p>"; | |
} | |
Map<String, List<String>> parameters = session.getParameters(); | |
Iterator<Map.Entry<String, List<String>>> iterator = parameters.entrySet().iterator(); | |
while (iterator.hasNext()) { | |
Map.Entry<String, List<String>> next = iterator.next(); | |
Log.d(TAG, "key:" + next.getKey() + ",value:" + next.getValue()); | |
} | |
String uri = session.getUri(); | |
if (REQUEST_ROOT.equals(session.getUri()) || session.getUri().equals("")) { | |
return responseImageList(); | |
} else { | |
return responseImage(session.getUri()); | |
// return responseDownloadImage(uri); | |
} | |
} | |
private String getMimeType(String filename) { | |
String mimetype = "text/html"; | |
if (filename.contains(".html") || filename.contains(".htm")) { | |
mimetype = "text/html"; | |
} else if (filename.contains(".js")) { | |
mimetype = "text/javascript"; | |
} else if (filename.contains(".css")) { | |
mimetype = "text/css"; | |
} else if (filename.contains(".gif")) { | |
mimetype = "text/gif"; | |
} else if (filename.contains(".jpeg") || filename.contains(".jpg")) { | |
mimetype = "image/jpeg"; | |
} else if (filename.contains(".png")) { | |
mimetype = "image/png"; | |
} else { | |
filename = "index.html"; | |
mimetype = "text/html"; | |
} | |
return mimetype; | |
} | |
@NonNull | |
private Response responseImageList() { | |
StringBuilder builder = new StringBuilder(); | |
builder.append("<!DOCTYPER html><html><body>"); | |
builder.append("<ol>"); | |
List<MediaBean> imagelist = ImageUtil.getImagelist(mContext); | |
for (int i = 0, len = imagelist.size(); i < len; i++) { | |
File file = new File(imagelist.get(i).path); | |
if (file.exists()) { | |
builder.append("<li> <a href=\"" + file.getPath() + "\">" + file.getName() + | |
"</a></li>"); | |
} | |
} | |
builder.append("<li>share counts: " + imagelist.size() + "</li>"); | |
builder.append("</ol>"); | |
builder.append("</body></html>\n"); | |
return newFixedLengthResponse(String.valueOf(builder)); | |
} | |
@NonNull | |
private Response responseImage(String uri) { | |
try { | |
String filename = uri.substring(1); | |
long start0 = System.currentTimeMillis(); | |
String mimeType = getMimeType(filename); | |
long cost2 = System.currentTimeMillis() - start0; | |
Log.d(TAG, "get mimeType using custom getMimeType:" + cost2); | |
long start = System.currentTimeMillis(); | |
String mimeTypeForFile = getMimeTypeForFile(uri);//don't use this method, time too long | |
long cost = System.currentTimeMillis() - start; | |
Log.d(TAG, "get mimeType using getMimeTypeForFile:" + cost); | |
FileInputStream fis = new FileInputStream(uri); | |
int available = fis.available(); | |
Response response = newFixedLengthResponse( | |
Response.Status.OK, | |
mimeType,//image can be see,mimeType must set "image/jpeg" || "image/jpg" || "image/png" | |
fis, | |
available); | |
response.addHeader("Content-Length", String.valueOf(available)); | |
return response; | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return newFixedLengthResponse(Response.Status.OK, "*/*", ""); | |
} | |
} | |
private Response responseDownloadImage(String uri) { | |
FileInputStream fis = null; | |
try { | |
fis = new FileInputStream(uri); | |
int available = fis.available(); | |
// 为了安全,判断下载的是否为合法允许的文件 | |
return newFixedLengthResponse(Response.Status.OK, "application/octet-stream", fis, available); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return newFixedLengthResponse("file not exists"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment