Spring boot-+-httpclient access API-+-Download PDF document Summary

Source: Internet
Author: User

Today, the project to do a demand, request the service of the download interface, but can not go directly to the access, to write a controller relay, in order to be able to do permissions control; Using Springboot,httpclient related technology, to achieve this function in a few steps I would like to say:

1. Write a controller (interface), to the front-end request

2. URL for forwarding to other services via HttpClient

3. Get the HttpClient stream and write to the target path (save)

4. Get the file stream from the target path to complete the download (if required)

Here's a step-by-step saying:

1.Controller: The control layer is to wrap up these functions, look at the code:

@ApiOperation (value = "Get pdf", notes = "Get PDF", consumes = "application/pdf")
    @PostMapping (Path = "Getpdf")
    public void Getpdf (@RequestBody appscaninput appscaninput, httpservletresponse response) {      
//Default download path (this path is well understood)
        String classpath = SecurityScanController.class.getClassLoader (). GetResource (""). GetPath ();
        String Savefilepath = classpath + "pdf/" + appscaninput.getname () + ". pdf";
To determine whether the file already exists, does not exist, write httpclient to tune the download interface
        file file =new file (savefilepath);
        if (!file.exists ()) {
//download PDF files from other services to this service
            Downloadpdfinsystem (Savefilepath, appscaninput);
        }
This service is downloaded to the client
        pdfdownload (response, appscaninput);
    


Note: Here is downloaded from other services PDF file to this service, and then downloaded to the client from this service, are you understand.

The annotation above is Swaggerui annotation, note that this consumes = "application/pdf", nothing else to say 2. URLs forwarded to other services by httpclient

private void Downloadpdfinsystem (string path, Appscaninput appscaninput) {//other services Download interface URL String url_down_pdf = U
Rlconstants.domainurl_test + urlconstants.url_down_pdf;
        The initialization of the parameter encapsulation stream map<string, object> params = new hashmap<> ();
        File F = new file (path);
        InputStream in = null;
        String ScanType = Appscaninput.gettype ();
            try {params.put ("Scan_type", ScanType);
Params.put ("Hash", Appscaninput.getaa ());
            HttpClient send POST request, pay attention to see here more important, Dopost is a method, I posted below ...
Httpentity httpentity = Httputil.dopost (url_down_pdf, params);
Gets the input stream in = Httpentity.getcontent () from the returned httpentity;
            Write the file code, not much said outputstream OS = new FileOutputStream (f);
            int bytesread = 0;
            byte[] buffer = new byte[1024];
            while ((bytesread = in.read (buffer))!=-1) {os.write (buffer, 0, bytesread);
            } os.close ();
        In.close (); }catch (Exception e) {e.printstacktrace (); }
    }


2.HttpClient method of sending a request: Returns a httpentity (the interface returns everything here)

public static httpentity doPost (String URL, map<string, object> param) {closeablehttpclient httpclient =
        Httpclients.createdefault ();
        HttpPost HttpPost = new HttpPost (URL);
        Httppost.setheader ("Authorization", constpojo.authorization);
        Httpentity httpentity; Set the request and connection timeout requestconfig requestconfig = Requestconfig.custom (). SetSocketTimeout (1000). Setconnecttimeout (1
        Build ();
        Httppost.setconfig (Requestconfig);
                    try {if (null!= param) {//Set parameter if (Commonutil.isnotemptymap (param)) {
                    Urlencodedformentity encodedformentity = new urlencodedformentity (Sethttpparams (param), "UTF-8");
                Httppost.setentity (encodedformentity);
            } closeablehttpresponse response = Httpclient.execute (HttpPost);
            int statusCode = Response.getstatusline (). Getstatuscode (); SysTem.out.println ("StatusCode:" +statuscode);
                if (StatusCode = =) {header[] allheaders = Response.getallheaders ();
                
                Httpentity = Response.getentity ();
                System.out.println (Allheaders.tostring ());
                System.out.println (Httpentity.tostring ());
            return httpentity; } else {System.out.println ("Connection exception ...)
            ");
        } catch (Exception e) {//TODO ... e.printstacktrace ();
    return null; }


3. Get the HttpClient stream and write to the target path (save)

。。。。。。 There's nothing to write, and the third step is in the second code, pass.

4. Get the file stream from the target path to complete the download (if required)

This is

Pdfdownload (response, Appscaninput) this method.

public void Pdfdownload (HttpServletResponse res, appscaninput appscaninput) {String fileName = Appscaninput.getna
Me () + ". pdf";
        Set Header information Res.setheader ("Content-type", "Application/octet-stream");
        Res.setcontenttype ("Application/octet-stream");
        Res.setheader ("Content-disposition", "attachment;filename=" + filename);
        byte[] buff = new byte[1024];
        Bufferedinputstream bis = null;
        OutputStream OS = null;
        String classpath = SecurityScanController.class.getClassLoader (). GetResource (""). GetPath ();
        String Savefilepath = classpath + "pdf/" + appscaninput.getname () + ". pdf";
            try {os = Res.getoutputstream ();
            bis = new Bufferedinputstream (new FileInputStream (Savefilepath));
int i = bis.read (buff);
                Prevent Chinese garbled while (I!=-1) {os.write (buff, 0, buff.length);
                Os.flush ();
            i = bis.read (buff); }} CATCH (IOException e) {e.printstacktrace ();
                finally {if (bis!= null) {try {bis.close ();
                catch (IOException e) {e.printstacktrace ();
    }}//System.out.println ("Success"); }


This file download code is nothing to say, look at the code should be able to understand

Welcome all reader to express their views and learn from each other.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.