Android: HttpUtils & file upload and download of Xutils

  HttpUtils is a necessary tool class to solve the complicated upload and download files and various Get and post requests in the daily work process. Through this class, it is very convenient for open source to focus on the business of the interface, and there is no need to write such lengthy code. The following full text is organized around four central points, namely: HttpGet request, HttpPost request, downloading files and uploading files.

    HttpGet request. I believe that students who are engaged in the development of Android network applications will not be unfamiliar with this. Long-term development will allow everyone to accumulate the next reusable tool class. And xUtils helps us abstract and integrate those tool classes into a more extensible helper class. For example, HttpGet request, here is only a brief introduction to the key application methods. Please download the source code of xUtils to study the specific details. We have introduced enough to apply to our application development. The usual HttpGet request will hang a series of request parameters behind the request address, dragging out a long tail, which is very annoying. Here, an object similar to BasicNameValuePair can be directly encapsulated by the parameters of the HttpPost request. Go to the request method, save the trouble of splicing url, and also set the timeout time. In addition, a callback class is provided in the request method. This class has callback methods for processing different request results, such as callbacks during the request process, callbacks for successful requests, and callbacks for requests with errors. Look directly at the code below.

RequestParams params = new RequestParams();
        params.addQueryStringParameter("method", "info");
        params.addQueryStringParameter("access_token",
                "3.1042851f652496c9362b1cd77d4f849b.2592000.1377530363.3590808424-248414");

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpGetCacheExpiry(1000 * 10);
        http.send(HttpRequest.HttpMethod.GET,
                "https://pcs.baidu.com/rest/2.0/pcs/quota",
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        resultText.setText("conn...");
                    }

                    @Override
                    public void onLoading(long total, long current) {
                        resultText.setText(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(String result) {
                        resultText.setText("response:" + result);
                    }


                    @Override
                    public void onFailure(HttpException error, String msg) {
                        resultText.setText(msg);
                    }
                });
    HttpPost request. In order to unify the style of the request, the method of HttpPost request is almost the same as that of HttpGet. It also provides various callback methods corresponding to different results. You can see it by looking at the code below.

RequestParams params = new RequestParams();
        params.addQueryStringParameter("method", "mkdir");
        params.addQueryStringParameter("access_token", "3.1042851f652496c9362b1cd77d4f849b.2592000.1377530363.3590808424-248414");
        params.addBodyParameter("path", "/apps/测试应用/test文件夹");

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                "https://pcs.baidu.com/rest/2.0/pcs/file",
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        resultText.setText("conn...");
                    }

                    @Override
                    public void onLoading(long total, long current) {
                        resultText.setText(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(String result) {
                        resultText.setText("upload response:" + result);
                    }


                    @Override
                    public void onFailure(HttpException error, String msg) {
                        resultText.setText(msg);
                    }
                });
The following introduces a very practical function, which is to download files through the Http protocol, and no longer need to write a lot of code for downloading files in Android. Such a long code can be really maddening to debug. I still remember that I did a project before. There was a requirement to be able to download videos, and to support breakpoint downloads. I only wrote a download tool class for a day or two, plus debugging, I really gave everyone Driven crazy. If xUtils came out earlier at that time, it wouldn't have to be so passable to do that requirement at that time. HttpUtils provides developers with a very convenient download api, which can be downloaded through a few simple parameters, and even breakpoint download functions. code above.

HttpHandler handler = http.download(
                downloadAddrEdit.getText().toString(),
                "/sdcard/fileexplorer.apk",
                true, // if the target file exists, continue the download with the unfinished part.
                true, // if the download is from the request The file name is obtained from the returned information, and it will be renamed automatically after the download is complete.
                new RequestCallBack<File>() {

                    @Override
                    public void onStart() {
                        resultText.setText("conn...");
                    }

                    @Override
                    public void onLoading(long total, long current) {
                        resultText.setText(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(File result) {
                        resultText.setText("downloaded:" + result.getPath());
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        resultText.setText(error.getExceptionCode() + ":" + msg);
                    }
                });
Note: If you need to suspend the download during the download process, you only need a simple line of code to achieve: mHandler.stop(). If you set a breakpoint to download, the next time it will restart, it will automatically start from the breakpoint of the last download. Download continues.

The last function introduced is to upload files, which is also very common in projects. For example, a user uploads an avatar, another example is a network disk application that needs to upload a local file to the cloud, and so on. At the same time, HttpUtils also provides developers with various callback interfaces during the upload process and the upload result. When you use HttpUtils to upload files, you can basically meet the needs of the business as long as you follow the code below to code the code.

RequestParams params = new RequestParams();
        params.addQueryStringParameter("method", "upload");
        params.addQueryStringParameter("path", "/apps/test application/test.zip");
        // Please open access_tokenapi in Baidu The test page finds its own access_token
        params.addQueryStringParameter("access_token", "3.1042851f652496c9362b1cd77d4f849b.2592000.1377530363.3590808424-248414");
        params.addBodyParameter("file", new File("/sdcard/test.zip");


        http.send(HttpRequest.HttpMethod.POST,
                "https://pcs.baidu.com/rest/2.0/pcs/file",
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        resultText.setText("conn...");
                    }

                    @Override
                    public void onLoading(long total, long current) {
                        resultText.setText(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(String result) {
                        resultText.setText("upload response:" + result);
                    }


                    @Override
                    public void onFailure(HttpException error, String msg) {
                        resultText.setText(msg);
                    }
                });

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326686021&siteId=291194637