Http调用Excel下载接口

1.功能需求

最近做的接口迁移的项目,将项目A的所有管理台接口迁移到项目B中,因为B项目的管理台的导航菜单的数据库是单独的环境,所以就需要先把项目A的所有管理台接口迁移到新项目B中 ,然后再从拥有导航菜单环境的项目C去调用项目B迁移过来的接口。
管理台的接口就是增删改查和Excel下载的接口,可以直接调用下面的HttpUtil或HttpClient写好的接口远程调用,因为项目C没有注册到注册中心,其实这里也可是使用Fegin调用接口

2.实现方式

例:
1.get请求的查询传参及返回
调用下面HttpUtil.httpGet()或者HttpClient.sendGet()即可,返回的数据从json字符串转为java对象再返回到前端

//ImsTeResponse是这个项目的公共返回类,根据自己项目更改
String responseStr = HttpUtil.httpGet(httpUrl);
ImsTeResponse imsTeResponse = JSONObject.parseObject(resopnseStr,ImsTeResponse.class);
return imsTeResponse;

2.post请求传参

//object 为post请求传入的实体类对象
String responseStr = HttpUtil.httpPost(url,JSON.toJSONString(object));
ImsTeResponse imsTeResponse = JSONObject.parseObject(resopnseStr,ImsTeResponse.class);
return imsTeResponse;

3.调用get请求实现Excel文件下载

return httpExportGet(url,httpServletResponse);

调用get请求或post请求还算容易,都是传参数或者对象,被调用端返回的数据都可以使用json格式展示,可以直接转java对象返回前端
但是使用Http调用Excel文件下载接口,获取文件数据再返给前端就稍微麻烦,需要获取Excel文件的json流再把流返给前端,一般文件下载会传一个HttpServletResponse对象,直接使用这个response对象写出流就行了也就是我下面写的HttpUtil.httpExportGet()方法,就可以实现调用另一个服务的Excel下载接口在前端实现文件下载。

3.HttpUtil

这里的get请求是直接传的url,所有参数都要拼接在url后面一起传过去,推荐使用下面HttpClient的get请求方式,参数是set进去的

package com.nb.easy.easyframe.module.archievs.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * Http请求工具类
 */
public class HttpUtil {
    /**
     * 连接超时时间,单位/毫秒
     */
    private static final int HTTP_TIMEOUT_CONNECTION = 30*1000;
    /**
     * 读取响应超越时间,单位/毫秒
     */
    private static final int HTTP_TIME_READ = 30*1000;
    /**
     * 读取参数格式
     */
    private static final String CONTENT_TYPE = "application/json;charset=utf-8";

    /**
     * GET请求返回String
     * @param httpUrl 参数
     * @return String
     * @throws java.net.MalformedURLException
     */
    public static String httpGet(String httpUrl) throws MalformedURLException {
        if ("".equals(httpUrl) || httpUrl == null){
            return "";
        }
        String getStr = "";
        InputStream  inputStream = null;
        try{
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION);
            connection.setReadTimeout(HTTP_TIME_READ);
            connection.setRequestProperty("Content-Type",CONTENT_TYPE);
            connection.connect();
            if (HttpURLConnection.HTTP_OK != connection.getResponseCode()){
                return "";
            }
            inputStream = connection.getInputStream();
            //数据流转换
            getStr = inputStreamToString(inputStream);
        } catch (IOException e) {
            return null;
        }finally {
            try {
                if (null != inputStream){
                    inputStream.close();
                }
            }catch (IOException e){
                return null;
            }
        }
        return getStr;
    }

    /**
     * Post请求返回String
     * @param httpUrl
     * @param data
     * @return
     */
    public static String httpPost(String httpUrl,String data){
        if ("".equals(httpUrl) || null == httpUrl){
            return "";
        }
        OutputStream outputStream = null;
        String postStr = "";
        InputStream inputStream = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION);
            connection.setReadTimeout(HTTP_TIME_READ);
            connection.setRequestProperty("Content-Type",CONTENT_TYPE);
            //这两个方法post必须开启
             connection.setDoInput((true));
             connection.setDoOutput(true);
             connection.connect();
             //打开输入流
            outputStream = connection.getOutputStream();
            //往输入流中写入我们需要传入服务器的数据
            outputStream.write(data.getBytes());
            outputStream.flush();
            //判断是否响应成功(其实就是tcp/ip三次握手是否成功)
            if (HttpURLConnection.HTTP_OK != connection.getResponseCode()){
                return "";
            }
            //获取服务器返回的数据
            inputStream = connection.getInputStream();
            //转换数据为String格式
            postStr = inputStreamToString(inputStream);
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != outputStream){
                    outputStream.close();
                }
                if (null != inputStream){
                    inputStream.close();
                }
                if (null != connection) {
                    connection.disconnect();
                }
            }catch (IOException e){
                return null;
            }
        }
        return postStr;
    }

    /**
     * 服务调用端接收-被调用端文件下载接口返回的excel数据,数据转换之后在返给前台
     * @param httpUrl
     * @param response
     * @return String 返回类型为通用返回类,这里使用String代替
     */
    public String httpExportGet(String httpUrl, HttpServletResponse response){
        if ("".equals(httpUrl) || httpUrl == null){
            return "";
        }
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION);
            connection.setReadTimeout(HTTP_TIME_READ);
            connection.setRequestProperty("Content-Type",CONTENT_TYPE);
            connection.connect();
            if (HttpURLConnection.HTTP_OK != connection.getResponseCode()){
                return "";
            }
            inputStream = connection.getInputStream();
            //输入流转输出流输出
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            byte[] bytes = new byte[1024];
            outputStream = response.getOutputStream();
            int count = -1;
            while ((count = inputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,count);
            }
            outputStream.flush();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "文件下载成功";
    }

    /**
     * 数据流转换
     * @param inputStream
     * @return String
     * @throws IOException
     */
    public static String inputStreamToString(InputStream inputStream) throws IOException {
        if (null == inputStream){
            return null;
        }
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer stringBuffer = new StringBuffer("");
        String line = null;
        try{
            while ((line = reader.readLine()) != null){
                stringBuffer.append(line + "\n");
            }
        }catch (IOException e){
            return null;
        }
        return stringBuffer.toString();
    }

}

4.HttpClientUtil

package com.nb.easy.easyframe.module.archievs.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

public class HttpClientUtil {
    /**
     * 读取参数格式
     */
    private static final String CONTENT_TYPE = "application/json;charset=utf-8";

    /**
     * Get请求
     * @param url
     * @param paraMap
     * @return String
     * @throws Exception
     */
    public static String sendGet(String url, Map<String, Object> paraMap) throws Exception{
        String content = "";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try{
            URIBuilder uriBuilder = new URIBuilder(url);
            if (null != paraMap && paraMap.size() > 0){
                for (Map.Entry<String,Object> entry : paraMap.entrySet()){
                    if (entry.getValue() != null){
                        uriBuilder.setParameter(entry.getKey(),entry.getValue().toString());
                    }
                }
            }
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.setHeader("Content-Type",CONTENT_TYPE);
            httpClient = HttpClients.createDefault();
            httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity);
        }finally {
            try {
                if (null != httpResponse){
                    httpResponse.close();
                }
                if (null != httpClient){
                    httpClient.close();
                }
            }catch (Exception e){
                return null;
            }
        }
        return content;
    }

    /**
     * Post请求
     * @param url
     * @param jsonStr
     * @return String
     * @throws Exception
     */
    public static String sendPost(String url, String jsonStr) throws Exception{
        String content = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type",CONTENT_TYPE);
        CloseableHttpResponse httpResponse = null;
        try{
            httpPost.setEntity(new StringEntity(jsonStr,"utf-8"));
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity,"utf-8");
        }finally {
            try {
                if (null != httpResponse){
                    httpResponse.close();
                }
                if (null != httpClient){
                    httpClient.close();
                }
            }catch (Exception e){
                return null;
            }
        }
        return content;
    }

    /**
     * Put请求
     * @param url
     * @param jsonStr
     * @return String
     */
    public static String sendPut(String url,String jsonStr){
        String content = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .setSocketTimeout(6000)
                .build();
        httpPut.setConfig(requestConfig);
        httpPut.setHeader("Content-Type",CONTENT_TYPE);
        CloseableHttpResponse httpResponse = null;
        try{
            httpPut.setEntity(new StringEntity(jsonStr,"utf-8"));
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity,"utf-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != httpResponse){
                    httpResponse.close();
                }
                if (null != httpClient){
                    httpClient.close();
                }
            }catch (Exception e){
                return null;
            }
        }
        return content;
    }

    /**
     * Delete请求
     * @param url
     * @return String
     */
    public static String sendDelete(String url){
        String content = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        httpDelete.setHeader("Content-Type",CONTENT_TYPE);
        CloseableHttpResponse httpResponse = null;
        try{
            httpResponse = httpClient.execute(httpDelete);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity,"utf-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != httpResponse){
                    httpResponse.close();
                }
                if (null != httpClient){
                    httpClient.close();
                }
            }catch (Exception e){
                return null;
            }
        }
        return content;
    }



}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值