JAVA常用工具类(3)

1、HttpClient的表单请求 1

1.1 示例方法

用于传递参数以及图片。示例中的方法是传递多个参数和图片。
示例:IP:port/url?id=1&name=2&… 然后带有两张图片和一个json对象(String类型),一共四种类型


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

import com.uniview.config.BaseConfig;
import com.uniview.config.BlockingQueueConfig;
import com.uniview.task.DownloadPicTask;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.HttpStatus;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.*;



@Slf4j
@Service
public class HttpClientUtil {

    @Autowired
    private BaseConfig baseConfig;

    private int faceidcount = 1;

    /**
     * 下载图片线程池
     */
    private static ThreadFactory downloadThreadFactory = new ThreadFactoryBuilder().setNameFormat("download-pool-%d").build();
    private static ThreadPoolExecutor downLoadThreadPool = new ThreadPoolExecutor(4,
            8,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024),
            downloadThreadFactory,
            new ThreadPoolExecutor.AbortPolicy());

    public String filePost(JSONObject face) {
        try {

            JSONObject mdFace = face.getJSONArray("FaceObject").getJSONObject(0);

            Map<String, String> headParam = new HashMap<>();
            //设备编号
            String puid = mdFace.getString("CameraID");
            headParam.put("puid", puid);
            
            //抓拍时间
            String zptime = mdFace.getString("SzFaceSnapTime" + "0000");
            headParam.put("zptime", zptime);
            
			...其它参数

            StringBuffer sb = new StringBuffer();

           
            for (Map.Entry<String, String> entry : headParam.entrySet()) {
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                sb.append("&");
            }

            String url = baseConfig.getIp() + ":" + baseConfig.getPort() + "/test/upload_pic.php?" + sb.toString();
            int i = url.lastIndexOf("&");
            url = url.substring(0, i);
            URL urlObj = new URL(url);
            // 连接
            HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
            /**
             * 设置关键值
             */
            con.setReadTimeout(60000);
            con.setConnectTimeout(60000);
            // 以Post方式提交表单,默认get方式
            con.setRequestMethod("POST");
            con.setDoInput(true);
            con.setDoOutput(true);
            // post方式不能使用缓存
            con.setUseCaches(false);
            // 设置请求头信息
            con.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*");
            con.setRequestProperty("Accept-Language", "zh-cn");
            ...请求头,根据需求来定
			
            //先写死吧
            con.setRequestProperty("Content-Length", "2740000");
            con.setRequestProperty("Connection", "close");
            con.setRequestProperty("Cache-Control", "no-cache");

            //这里获取图片
            Map<String, byte[]> maps = new HashMap();
            String XImageID = "";
            String DImageID = "";
            String XPlatePic = "";
            String DPic = "";

            JSONObject MDSubImageList = mdFace.getJSONObject("SubImageList");
            JSONArray SubImageInfoObject = MDSubImageList.getJSONArray("SubImageInfoObject");

            for (Object object : SubImageInfoObject) {
                JSONObject OneOfSubImageInfoObject = JSON.parseObject(object.toString());
                if (null != OneOfSubImageInfoObject && "11".equals(OneOfSubImageInfoObject.getString("Type"))) {
                    XImageID = OneOfSubImageInfoObject.getString("ImageID");
                    XPlatePic = OneOfSubImageInfoObject.getString("StoragePath");
                    // 下载小图
                    FutureTask<byte[]> faceTask = new FutureTask<>(new DownloadPicTask(XPlatePic));
                    downLoadThreadPool.execute(faceTask);
                    try {
                        byte[] bytes = faceTask.get();
                        maps.put("11", bytes);
                    } catch (Exception e) {
                        log.info("----------图片下载线程出错----------", e);
                        return null;
                    }
                }
                if (null != OneOfSubImageInfoObject && "14".equals(OneOfSubImageInfoObject.getString("Type"))) {
                    DImageID = OneOfSubImageInfoObject.getString("ImageID");
                    DPic = OneOfSubImageInfoObject.getString("StoragePath");
                    // 下载大图
                    FutureTask<byte[]> faceTask = new FutureTask<>(new DownloadPicTask(DPic));
                    downLoadThreadPool.execute(faceTask);
                    try {
                        byte[] bytes = faceTask.get();
                        maps.put("14", bytes);
                    } catch (Exception e) {
                        log.info("----------图片下载线程出错----------", e);
                        return null;
                    }
                }
            }

            OutputStream out = new DataOutputStream(con.getOutputStream());


            StringBuffer SB1 = new StringBuffer();
            //todo shenli
            SB1.append("\r\n");
            //<----------------------注意长短
			构造第一张图片请求头
            SB1.append("\r\n");
            SB1.append("Content-Disposition: form-data; name=\"userfile\"; pictype=0&isurl=0&piclen=13000;filename=\"" + XImageID + "\"");
            SB1.append("\r\n");
            SB1.append("Content-Type: image/pjpeg" + "\r\n");
            SB1.append("\r\n");
            byte[] head1 = SB1.toString().getBytes("utf-8");
            // 获得输出流

            // 输出表头
            out.write(head1);
            // 把文件已流文件的方式 推入到url中
            InputStream inputStream1 = new ByteArrayInputStream(maps.get("11"));
            DataInputStream in1 = new DataInputStream(inputStream1);

            int bytes1 = 0;
            byte[] bufferOut1 = new byte[1024];
            while ((bytes1 = in1.read(bufferOut1)) != -1) {
                out.write(bufferOut1, 0, bytes1);
            }
            in1.close();

            StringBuffer SB2 = new StringBuffer();
            SB2.append("\r\n");
            构造第二张图片请求头
            SB2.append("\r\n");
            SB2.append("Content-Disposition: form-data; name=\"userfile2\"; pictype=0&isurl=0&piclen=13000;filename=\"" + DImageID + "\"");
            SB2.append("\r\n");
            SB2.append("Content-Type: image/pjpeg" + "\r\n");
            SB2.append("\r\n");
            byte[] head2 = SB2.toString().getBytes("utf-8");
            // 获得输出流

            // 输出表头
            out.write(head2);
            // 把文件已流文件的方式 推入到url中
            InputStream inputStream2 = new ByteArrayInputStream(maps.get("14"));
            DataInputStream in2 = new DataInputStream(inputStream2);

            int bytes2 = 0;
            byte[] bufferOut2 = new byte[1024];
            while ((bytes2 = in2.read(bufferOut2)) != -1) {
                out.write(bufferOut2, 0, bytes2);
            }
            in2.close();

            //todo shenli
            StringBuffer faceData = new StringBuffer();
            faceData.append("\r\n");
            构造JSON字符串请求头
            faceData.append("\r\n");
            faceData.append("Content-Disposition: form-data; name=\"userfile3\"; datatype=json&datalen=126");
            faceData.append("\r\n");
            faceData.append("Content-Type: text/plain"+ "\r\n");
            faceData.append("\r\n");

            byte[] head3 = faceData.toString().getBytes("utf-8");
            // 获得输出流

            // 输出表头
            out.write(head3);
			
            JSONObject data = new JSONObject();
            //以下字段已与第三方沟通,没有明确,说是按照文档上的来就行
            String sName = mdFace.getString("Name");
            data.put("sName", sName);
            data.put("sNation", "");
            data.put("sBirthDate", "");
            data.put("sAddress", "");
            data.put("sIdNumber", "");
            data.put("sStartDate", "");
            data.put("sEndDate", "");
            data.put("sCheckDate", "");
            data.put("iResult", 0);
            data.put("bAlarm", true);
            data.put("sRec", "");

            InputStream dataInputStream = new ByteArrayInputStream(data.toJSONString().getBytes("UTF-8"));
            DataInputStream in3 = new DataInputStream(dataInputStream);
            int bytes3 = 0;
            byte[] bufferOut3 = new byte[1024];
            while ((bytes3 = in3.read(bufferOut3)) != -1){
                out.write(bufferOut3, 0, bytes3);
            }
            in3.close();

            // 结尾部分   定义最后数据分隔线
            StringBuffer endData = new StringBuffer();
            endData.append("\r\n");
            结尾标志
            endData.append("\r\n");
            byte[] end2 = endData.toString().getBytes("utf-8");
            // 获得输出流

            // 输出表头
            out.write(end2);

            out.flush();
            out.close();
            BufferedReader reader = null;
            try {
                //返回值
                int resultCode = con.getResponseCode();
                log.info("上传图片至第三方结果:" + resultCode + "," + con.getResponseMessage());
                if (HttpStatus.SC_OK == resultCode) {
                    // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)
                    BufferedReader bf = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName("utf-8")));
                    String line;
                    // 用来存储响应数据
                    StringBuilder sbResult = new StringBuilder();

                    // 循环读取流,若不到结尾处
                    while ((line = bf.readLine()) != null) {
                        sbResult.append(line);
                    }
                    bf.close();    // 重要且易忽略步骤 (关闭流,切记!)
                    con.disconnect(); // 销毁连接
                    return sbResult.toString();
                }
            } catch (IOException e) {
                //把数据重新存入阻塞队列中
                BlockingQueueConfig.faceBlockQueue.put(face.toJSONString());
                log.error("上传图片至第三方异常", e);

            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (Exception e2) {
            //把数据重新存入阻塞队列中
            try {
                BlockingQueueConfig.faceBlockQueue.put(face.toJSONString());
            } catch (InterruptedException e) {
                log.error("{}失败数据重新入队异常:{}", ConstantUtil.ERROR_LOG, e);
            }
            log.error("上传图片至第三方异常", e2);

        }
        return ConstantUtil.RESPONSE_FAIL;
    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile;
        if (file == null || file.equals("") || file.getSize() <= 0) {
            return null;
        } else {
            InputStream ins;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            log.error("输入流转file异常:", e);
        }
    }

}

1.2、模拟的表单接口

@Slf4j
@RestController
public class TestPostController {

    @PostMapping("/test/upload_pic")
    public String dataClassTabs(ParamModel paramModel, MultipartFile userfile, MultipartFile userfile2, String userfile3, HttpServletRequest request){

        System.out.println(paramModel.toString());
        System.out.println("file1是:" + userfile);
        System.out.println("file2是:" + userfile2);

        //JSONObject userfile3 = paramModel.getUserfile3();

        System.out.println("userfile3是:" + userfile3);


        //String cacheControl = request.getHeader("Cache-Control");
       // System.out.println("cacheControl是:" + cacheControl);
        int length = request.getContentLength();
        System.out.println("length是:" + length);

        String fileName = userfile.getName();
        String fileName2 = userfile2.getName();

        System.out.println("fileName是:" + fileName);
        System.out.println("fileName2是:" + fileName2);

        /*String path = "C:\\Users\\s07645\\Desktop\\SSHClient";

        File file = new File(path, fileName + ".jpg");
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file, false);
            fileOutputStream.write(userfile.getBytes(), 0, userfile.getBytes().length);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/


        return "1";
    }

}

HttpClient的表单请求 2

2.1 所需pom依赖

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.10</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.12</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.10</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.12</version>
        </dependency>

2.2 方法示例


import lombok.extern.slf4j.Slf4j;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import java.io.IOException;

/**
 * 调用Http Restful接口
 */
@Slf4j
@Component
public class HttpUtil {


    /**
     * 发送多数据格式的POST请求
     * @param url 请求路径
     * @param param 参数
     * @param picFile 需要发送的文件
     * @return 结果
     */
    public static BaseResponse postToVMMulti(String url, String param, byte[] picFile) {

        log.info("进入添加方法!!!");

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String resString;
        try {
            // 设置请求头
            HttpPost httpPost = new HttpPost(url);
            httpClient = HttpClients.createDefault();
            httpPost.setHeader("Authorization", "token");
            // 设置文件数据格式
            ContentType contentType = ContentType.create("text/plain","UTF-8");
            //需要设置MODE为RFC6532,否则上传到人脸库中文字符会变成乱码
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            entityBuilder.addTextBody("Info", param, contentType).addBinaryBody("Face", picFile);
            log.info("entityBuilder是:" + entityBuilder.toString());
            HttpEntity entity = entityBuilder.build();
            log.info("entity是:" + entity.toString());
            httpPost.setEntity(entity);

            // 发送请求
            httpResponse = httpClient.execute(httpPost);
            // 检查返回结果
            HttpEntity responseEntity = httpResponse.getEntity();
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            resString = EntityUtils.toString(responseEntity, "UTF-8");
            log.debug("添加返回的结果是:" + resString);

            if (200 != statusCode) {
                return BaseResponse.build(statusCode, "响应失败", resString);
            }
            return BaseResponse.build(200, "响应成功", resString);
        } catch (Exception e) {
            log.error("POST请求失败-->>" + e.getMessage(), e);
            return BaseResponse.build(100, "响应失败", e);
        } finally {
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    log.error("HttpResponse关闭失败-->>" + e.getMessage(), e);
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error("HttpClient关闭失败-->>" + e.getMessage(), e);
                }
            }
        }
    }



}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值