Android开发如何搭建超简易调试后台

做为一个Android开发,常常碰到项目周期紧张,然后台来不及写接口的状况。为了节约时间,本人特地向咱们公司的后台工程师请教了一下如何搭建一个简易的本地接口调试环境(SpringBoot)。废话很少说,掏出神器!java

新建项目

File -> New -> Project...
选择左侧Spring Initializr,选择jdk版本,点击Next 数组


填写 包名等相关信息,而后 Next

选择 Spring Web,继续 Next

填写工程 Name路径,最后点击 Finish

项目结构

总体的项目结构很相似AndroidStudio的项目目录,DemoApplication便是整个Web应用的入口,application.properties中能够配置应用的相关属性设置缓存


这里看一下 DemoApplication中的方法

新建接口

咱们最终须要实现的接口地址参考以下(端口号默认为8080):
http://localhost:8080/test/printMap
若须要指定端口号,则配置以下: app

localhost
本机地址,在本机上利用 Chrome或者 Postman等工具调试是直接使用 localhost便可,在 app中进行调试则须要指定该 localhost(能够在 cmdipconfig确认本机 IP)

建立test路径

com.example.demo 包下新建一 个HelloWorld 类(存放接口方法)以及一个bean目录(存放接收的数据)
maven

HelloWorld.java中标注路径
ide

建立目标接口

  1. 接收单个参数
    接口地址:http://localhost:8080/test/printString
    HelloWorld.java内建立接口方法:

测试: 工具

  1. 接收多个参数
    接口地址:http://localhost:8080/test/printMap
    bean目录下新建MultiParamTest.java来接收参数


HelloWorld.java内建立接口方法:

注:这里将multiParamTest对象转为Json对象用的是FastJson,添加方法以下(maven测试


测试:

  1. 上传单个文件
    接口地址:http://192.168.1.172:8080/test/uploadFile
    bean目录下新建UploadFile.java用于存放文件接收结果


HelloWorld.java内建立接口方法:

private File file = new File("d:"+File.separator+"files");
    /** * 上传文件 * * @param multipartFile 文件 * @return bean of UploadFile instance */
    @RequestMapping("uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {//若接收的文件为空,则返回false
            return JSON.toJSONString(new UploadFile(false, "accept none"));
        }
        if (!file.exists()) {//若用来存放文件的本地文件路径不存在则建立路径中的全部文件夹
            file.mkdirs();
        }
        BufferedOutputStream outputStream = null;//缓存输出流
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(file.getAbsolutePath() + "/" + multipartFile.getOriginalFilename()));
            outputStream = new BufferedOutputStream(fileOutputStream);
            outputStream.write(multipartFile.getBytes());
            outputStream.flush();
            return JSON.toJSONString(new UploadFile(true, "success"));//返回结果true,文件保存成功
        } catch (IOException e) {
            return JSON.toJSONString(new UploadFile(false, "error:" + e.getMessage()));//保存文件失败,返回结果false,返回失败缘由
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();//关闭输出流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
复制代码

测试:ui

  1. 上传多个文件及参数
    接口地址:http://192.168.1.172:8080/test/uploadFiles
    HelloWorld.java内建立接口方法:
/** * 接收多个文件及参数 * @param multipartFiles 文件数组 * @param multiParamTest 其余参数 * @return 上传结果 */
    @RequestMapping("uploadFiles")
    public String uploadFiles(@RequestParam("files") MultipartFile[] multipartFiles, MultiParamTest multiParamTest) {
        System.out.println("接收多个文件,param=" + JSON.toJSONString(multiParamTest));
        if (multipartFiles.length == 0) {
            return JSON.toJSONString(new UploadFile(false, "Detect No Files"));
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        String result = null;
        for (MultipartFile multipartFile : multipartFiles) {
            if (multipartFile == null) {
                result = JSON.toJSONString(new UploadFile(false, "accept none"));
                continue;
            }
            BufferedOutputStream outputStream = null;
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(new File(file.getAbsolutePath() + "/" + multipartFile.getOriginalFilename()));
                outputStream = new BufferedOutputStream(fileOutputStream);
                outputStream.write(multipartFile.getBytes());
                outputStream.flush();
                result = JSON.toJSONString(new UploadFile(true, "success"));
            } catch (IOException e) {
                result = JSON.toJSONString(new UploadFile(false, "error:" + e.getMessage()));
                break;
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
复制代码

配置接收文件大小限制(-1为不限制大小,或者eg:50MB):spa

测试:

app上测试

新建一个JavaWebDemo工程用来测试(RxJava+Retrofit):

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://192.168.1.172:8080/test/")
                .build();

        Map<String, String> param = new HashMap<>();
        param.put("str1", "123");
        param.put("str2", "w234");

        String filePath1 = "storage"+File.separator+"emulated/0/bluetooth/xx.apk";
        String filePath2="storage/emulated/0/DingTalk/xx_1.apk";
        Observable<BeanUpLoadFile> upLoadFileObservable = retrofit.create(Api.class)
                .uploadFile(createReportParam("files", filePath1,filePath2),param);
        upLoadFileObservable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BeanUpLoadFile>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BeanUpLoadFile beanUpLoadFile) {
                        Log.i(MainActivity.class.getSimpleName(), beanUpLoadFile.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(MainActivity.class.getSimpleName(),e.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /** * 生成上传文件的参数 */
    public MultipartBody.Part[] createReportParam(String paramName, String... filePath) {
        MultipartBody.Part[] parts = new MultipartBody.Part[filePath.length];
        for (int i=0;i<filePath.length; i++) {
            File uploadFile = new File(filePath[i]);
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), uploadFile);
            parts[i]=MultipartBody.Part.createFormData(paramName, uploadFile.getName(), requestBody);
        }

        return parts;
    }
}
复制代码

app打印接收接口结果日志:


接口后台接收到的数据:
相关文章
相关标签/搜索