上篇中实现了访问APP中内置的静态网页 移动端搭建Http Server(六)—— 实现APP中内置静态网页,本篇会继续实现另一个功能——wifi传图
1.实现思路
- ImageUploadHandler中读取图片二进制数据并保存到文件
- 将图片路径回调给Activity验证结果
- 使用Post man模拟HTTP Post请求(到google store中安装postman需用到代理工具)
2.重新实现一下UploadImageHandler的handle方法
@Override
public void handle(String uri, HttpContext httpContext) throws IOException {
String tempPath = "/mnt/sdcard/test_upload.jpg";
Long totalLength = Long.valueOf(httpContext.getRequestHeaderValue("Content-Length"));// 收取到的文件的长度
FileOutputStream fos = new FileOutputStream(tempPath);
InputStream in = httpContext.getUnderlySocket().getInputStream();
byte[] buffer = new byte[10240];
int nReaded = 0; //从流读到buffer中实际的字节长度
long nLeftLength = totalLength;// 剩余还需要读的字节数
while ((nReaded = in.read(buffer)) > 0 && nLeftLength > 0) {
fos.write(buffer, 0, nReaded);
nLeftLength -= nReaded;
}
fos.close();
OutputStream os = httpContext.getUnderlySocket().getOutputStream();
PrintStream printStream = new PrintStream(os);
printStream.println("HTTP/1.1 200 OK");
//输出\r\n (不能写错)
printStream.println();
onImageLoaded(tempPath);
}
protected void onImageLoaded(String path){
}
将接收到的文件保存到sd卡,然后返回路径
3.在Activity中进行回调
mSimpleServer.registerResourceHandler(new UploadImageHandler(this){
@Override
protected void onImageLoaded(String path) {
showImage(path);
}
});
private void showImage(final String path) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeFile(path);
mImageView.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, "image received and shown", Toast.LENGTH_SHORT).show();
}
});
}
4.用Postman验证一下
点击Send,然后点击了Cancel Request(不知道为什么点Cancel才能看到结果)看到了结果
至此,本系列博文已完毕,可以在现有的功能基础上改善和开发。
github源码地址:https://github.com/jianiuqi/AndroidServer