As an Android developer, it’s often the case that the project cycle is tight and the background doesn’t have enough time to write interfaces. In order to save time, I specially asked our company’s background engineers how to build a simple local interface debugging environment (SpringBoot). No more nonsense, out of the artifact!

New project

File -> New -> Project… Select Spring Initializr on the left, select the JDK version, and click Next



The package name
Next



Spring Web
Next



Name
The path
Finish

The project structure

The overall project structure is similar to the project directory in AndroidStudio. DemoApplication is the entrance to the entire Web application. Application



DemoApplication

The new interface

Refer to below the address we eventually need to implement the interface (port number is 8080 by default) : http://localhost:8080/test/printMap if you need to specify the port number, the configuration is as follows:

localhost



Chrome
Postma
localhost
app
localhost
cmd
ipconfig
IP

Creating a test path

Create a new HelloWorld class (to hold interface methods) and a bean directory (to hold received data) under the com.example.demo package.

Annotate paths in helloWorld.java

Creating the target Interface

  1. Receive a single parameter interface address: http://localhost:8080/test/printString in the HelloWorld. Java created within the interface methods:

Testing:

  1. Receive multiple parameter interface address: http://localhost:8080/test/printMap in bean directory MultiParamTest. New Java to receive the parameters



HelloWorld.java

To convert the multiParamTest object to Json using FastJson, add the following method (maven) :





  1. Upload a single file interface address: http://192.168.1.172:8080/test/uploadFile in bean directory new UploadFile. Java is used to store file receiving results



HelloWorld.java

    private File file = new File("d:"+File.separator+"files");
    /** * Upload file **@paramMultipartFile file *@return bean of UploadFile instance
     */
    @RequestMapping("uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {// Return false if the received file is empty
            return JSON.toJSONString(new UploadFile(false."accept none"));
        }
        if(! file.exists()) {// Create all folders in the local file path if it does not exist
            file.mkdirs();
        }
        BufferedOutputStream outputStream = null;// Cache the output stream
        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"));// Returns true, the file is saved successfully
        } catch (IOException e) {
            return JSON.toJSONString(new UploadFile(false."error:" + e.getMessage()));// Failed to save the file, false is returned, failure cause is returned
        } finally {
            try {
                if(outputStream ! =null) {
                    outputStream.close();// Close the output stream}}catch(IOException e) { e.printStackTrace(); }}}Copy the code

Testing:

  1. Upload multiple files and parameter interface address: http://192.168.1.172:8080/test/uploadFiles in the HelloWorld. Java created within the interface methods:
    /** * Receive multiple files and parameters *@paramMultipartFiles File array *@paramMultiParamTest Other parameters *@returnUpload result */
    @RequestMapping("uploadFiles")
    public String uploadFiles(@RequestParam("files") MultipartFile[] multipartFiles, MultiParamTest multiParamTest) {
        System.out.println("Receive multiple files,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;
    }
Copy the code

Configure the received file size limit (-1 indicates unrestricted size, or eg:50MB) :

The test on the app

Create a JavaWebDemo project to test (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(a) {}}); }/** * Generates parameters for uploading files */
    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);
        }

        returnparts; }}Copy the code

App prints the receiving interface result log: