java模拟http请求,通过流的方式发送数据,模拟接收流文件和json数据

项目里碰到过模拟ajax请求的案例,研究了一下,觉得 httpClient 是真心好用,由于模拟环境搞了大半天,httpclient就另外再写博文吧

下面的例子介绍流的方式发送和接收,这个就有点暴力了,想传啥都行:以字节流的方式发送数据(可以是任何数据)

看标题就知道了,简单粗暴的方法,管他什么格式,统统“流”过去,不过既然是模拟的,要配置好其他参数,对方才能正常接收到

发送方:

    /**
     * 以流的方式
     * 发送文件和json对象
     *
     * @return
     */
    public static String doPostFileStreamAndJsonObj(String url, List<String> fileList, JSONObject json) {
        String result = "";//请求返回参数
        String jsonString = json.toJSONString();//获得jsonstirng,或者toString都可以,只要是json格式,给了别人能解析成json就行
//        System.out.println("================");
//        System.out.println(xml);//可以打印出来瞅瞅
//        System.out.println("================");
        try {
            //开始设置模拟请求的参数,额,不一个个介绍了,根据需要拿
            String boundary = "------WebKitFormBoundaryUey8ljRiiZqhZHBu";
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("connection", "Keep-Alive");
            //这里模拟的是火狐浏览器,具体的可以f12看看请求的user-agent是什么
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Charsert", "UTF-8");
            //这里的content-type要设置成表单格式,模拟ajax的表单请求
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            // 指定流的大小,当内容达到这个值的时候就把流输出
            conn.setChunkedStreamingMode(10240000);
            //定义输出流,有什么数据要发送的,直接后面append就可以,记得转成byte再append
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();// 定义最后数据分隔线

            StringBuilder sb = new StringBuilder();
            //添加form属性
            sb.append("--");
            sb.append(boundary);
            sb.append("\r\n");
            //这里存放要传输的参数,name = xml
            sb.append("Content-Disposition: form-data; name=\"JsonObj\"");
            sb.append("\r\n\r\n");
            //把要传的json字符串放进来
            sb.append(jsonString);
            out.write(sb.toString().getBytes("utf-8"));
            out.write("\r\n".getBytes("utf-8"));

            int leng = fileList.size();
            for (int i = 0; i < leng; i++) {
                File file = new File(fileList.get(i));
                if(file.exists()){
                    sb = new StringBuilder();
                    sb.append("--");
                    sb.append(boundary);
                    sb.append("\r\n");
                    //这里的参数啥的是我项目里对方接收要用到的,具体的看你的项目怎样的格式
                    sb.append("Content-Disposition: form-data;name=\"File"
                            + "\";filename=\"" + file.getName() + "\"\r\n");
                    //这里拼接个fileName,方便后面用第一种方式接收(如果是纯文件,不带其他参数,就可以不用这个了,因为Multipart可以直接解析文件)
                    sb.append("FileName:"+ file.getName() + "\r\n");
                    //发送文件是以流的方式发送,所以这里的content-type是octet-stream流
                    sb.append("Content-Type:application/octet-stream\r\n\r\n");
                    byte[] data = sb.toString().getBytes();
                    out.write(data);
                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    int j = i + 1;
                    if (leng > 1 && j != leng) {
                        out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个
                    }
                    in.close();
                }else{
                    System.out.println("没有发现文件");
                }
            }
            //发送流
            out.write(end_data);
            out.flush();
            out.close();
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                result += line;
            }
//            System.out.println("================");
//            System.out.println(result.toString());//可以把结果打印出来瞅瞅
//            System.out.println("================");
            //后面可以对结果进行解析(如果返回的是格式化的数据的话)
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!" + e);
            e.printStackTrace();
        }
        return result;
    }
   public static void main(String args[]) throws Exception {
        //模拟流文件及参数上传
        String url = "http://127.0.0.1:8090/kty/test/receiveStream";
        //文件列表,搞了三个本地文件
        List<String> fileList = new ArrayList<>();
        fileList.add("F:\\me\\photos\\动漫\\3ba39425fec1965f4d088d2f.bmp");
        fileList.add("F:\\me\\photos\\动漫\\09b3970fd3f5cc65b1351da4.bmp");
        fileList.add("F:\\me\\photos\\动漫\\89ff57d93cd1b72cd0164ec9.bmp");
        //json字符串,模拟了一个,传图片名字吧
        String jsonString = "{\n" +
                "    \"token\": \"stream data\", \n" +
                "    \"content\": [\n" +
                "        {\n" +
                "            \"id\": \"1\", \n" +
                "            \"name\": \"3ba39425fec1965f4d088d2f.bmp\"\n" +
                "        }, \n" +
                "        {\n" +
                "            \"id\": \"2\", \n" +
                "            \"name\": \"09b3970fd3f5cc65b1351da4.bmp\"\n" +
                "        }, \n" +
                "        {\n" +
                "            \"id\": \"3\", \n" +
                "            \"name\": \"89ff57d93cd1b72cd0164ec9.bmp\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        JSONObject json = JSONObject.parseObject(jsonString);
        doPostFileStreamAndJsonObj(url, fileList, json);
    }

因为是流的方式,所以要从http请求里获取body,然后再解析

接收方:


@RestController
@RequestMapping("/test")
//跨域注解
@CrossOrigin
public class TestController {

    /**
     * 接收流信息
     *
     * @param request
     * @return
     */
    @PostMapping("/receiveStream")
    public String receiveStream(HttpServletRequest request) {
        String result = "";
        System.out.println("进来了");
        try {
            //获取request里的所有部分
            Collection<Part> parts = request.getParts();
            for (Iterator<Part> iterator = parts.iterator(); iterator.hasNext(); ) {
                Part part = iterator.next();
                System.out.println("名称========" + part.getName());
                if ("JsonObj".equals(part.getName())) {
                    //解析json对象
                    BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream()));
                    String line = "";
                    String parseString = "";
                    while ((line = reader.readLine()) != null) {
                        parseString += line;
                    }
                    JSONObject json = JSONObject.parseObject(parseString);
                    System.out.println("接收到的json对象为=====" + json.toJSONString());
                } else if ("File".equals(part.getName())) {
                    String fileName = "";
                    Long size = part.getSize();
                    //文件名的获取,可以直接获取header里定义好的FIleName(大部分没有),或从Content-Disposition去剪切出来
//                    String head = part.getHeader("Content-Disposition");
//                    fileName = head.substring(head.indexOf("filename=")+ 10, head.lastIndexOf("\""));
                    fileName = part.getHeader("FileName");
                    System.out.println(fileName + size);
//                    //这里就是文件,文件流就可以直接写入到文件了
//                    InputStream inputStream = part.getInputStream();
//                    OutputStream outputStream = new FileOutputStream(fileName);
//                    int bytesWritten = 0;
//                    int byteCount = 0;
//                    byte[] bytes = new byte[1024];
//                    while ((byteCount = inputStream.read(bytes)) != -1) {
//                        outputStream.write(bytes, bytesWritten, byteCount);
//                        bytesWritten += byteCount;
//                    }
//                    inputStream.close();
//                    outputStream.close();
                }
            }

            //如果嫌上面获取文件的麻烦,用下面这个比较简单,解析成multipartFile
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //统计文件数
            Integer fileCount = 0;
            //请求里key为File的元素(即文件元素)
            List<MultipartFile> list = multiRequest.getFiles("File");
            while (fileCount < list.size()) {
                MultipartFile file = list.get(fileCount);
                System.out.println(file.getName());
                System.out.println(file.getOriginalFilename());
                System.out.println(file.getSize());
                fileCount++;
            }
            System.out.println("共有" + fileCount + "个文件");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

控制台输出:

 

流的方式到这里就结束了,

httpclient的方式稍后再写

如果模拟的时候有相关参数不了解,可以浏览器打开随便一个网页,f12看看传的参数都有哪些,例如:

欢迎留言指正

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章