2023年8月1日发(作者:)
java模拟http请求,通过流的⽅式发送数据,模拟接收流⽂件和json数据项⽬⾥碰到过模拟ajax请求的案例,研究了⼀下,觉得 httpClient 是真⼼好⽤,由于模拟环境搞了⼤半天,httpclient就另外再写博⽂吧下⾯的例⼦介绍流的⽅式发送和接收,这个就有点暴⼒了,想传啥都⾏:以字节流的⽅式发送数据(可以是任何数据)看标题就知道了,简单粗暴的⽅法,管他什么格式,统统“流”过去,不过既然是模拟的,要配置好其他参数,对⽅才能正常接收到发送⽅: /** * 以流的⽅式 * 发送⽂件和json对象 * * @return */ public static String doPostFileStreamAndJsonObj(String url, List fileList, JSONObject json) { String result = "";//请求返回参数 String jsonString = String();//获得jsonstirng,或者toString都可以,只要是json格式,给了别⼈能解析成json就⾏// n("================");// n(xml);//可以打印出来瞅瞅// n("================"); try { //开始设置模拟请求的参数,额,不⼀个个介绍了,根据需要拿 String boundary = "------WebKitFormBoundaryUey8ljRiiZqhZHBu"; URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) nnection(); utput(true); nput(true); Caches(false); uestMethod("POST"); uestProperty("connection", "Keep-Alive"); //这⾥模拟的是⽕狐浏览器,具体的可以f12看看请求的user-agent是什么 uestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); uestProperty("Charsert", "UTF-8"); //这⾥的content-type要设置成表单格式,模拟ajax的表单请求 uestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); // 指定流的⼤⼩,当内容达到这个值的时候就把流输出 nkedStreamingMode(10240000); //定义输出流,有什么数据要发送的,直接后⾯append就可以,记得转成byte再append OutputStream out = new DataOutputStream(putStream()); byte[] end_data = ("rn--" + boundary + "--rn").getBytes();// 定义最后数据分隔线 StringBuilder sb = new StringBuilder(); //添加form属性 ("--"); (boundary); ("rn"); //这⾥存放要传输的参数,name = xml ("Content-Disposition: form-data; name="JsonObj""); ("rnrn"); //把要传的json字符串放进来 (jsonString); (ng().getBytes("utf-8")); ("rn".getBytes("utf-8")); int leng = (); for (int i = 0; i < leng; i++) { File file = new File((i)); if(()){ sb = new StringBuilder(); ("--"); ("--"); (boundary); ("rn"); //这⾥的参数啥的是我项⽬⾥对⽅接收要⽤到的,具体的看你的项⽬怎样的格式 ("Content-Disposition: form-data;name="File" + "";filename="" + e() + ""rn"); //这⾥拼接个fileName,⽅便后⾯⽤第⼀种⽅式接收(如果是纯⽂件,不带其他参数,就可以不⽤这个了,因为Multipart可以直接解析⽂件) ("FileName:"+ e() + "rn"); //发送⽂件是以流的⽅式发送,所以这⾥的content-type是octet-stream流 ("Content-Type:application/octet-streamrnrn"); byte[] data = ng().getBytes(); (data); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = (bufferOut)) != -1) { (bufferOut, 0, bytes); } int j = i + 1; if (leng > 1 && j != leng) { ("rn".getBytes()); // 多个⽂件时,⼆个⽂件之间加⼊这个 } (); }else{ n("没有发现⽂件"); } } //发送流 (end_data); (); (); // 定义BufferedReader输⼊流来读取URL的响应 BufferedReader reader = new BufferedReader(new InputStreamReader( utStream())); String line = ""; while ((line = ne()) != null) { result += line; }// n("================");// n(ng());//可以把结果打印出来瞅瞅// n("================"); //后⾯可以对结果进⾏解析(如果返回的是格式化的数据的话) } catch (Exception e) { n("发送POST请求出现异常!" + e); tackTrace(); } return result; } public static void main(String args[]) throws Exception { //模拟流⽂件及参数上传 String url = "127.0.0.1:8090/kty/test/receiveStream"; //⽂件列表,搞了三个本地⽂件 List fileList = new ArrayList<>(); ("F:mephotos动漫"); ("F:mephotos动漫"); ("F:mephotos动漫"); //json字符串,模拟了⼀个,传图⽚名字吧 String jsonString = "{n" + " "token": "stream data", n" + " "content": [n" + " {n" + " "id": "1", n" + " "name": ""n" + " }, n" + " {n" + " "id": "2", n" + " "name": ""n" + " }, n" + " {n" + " "id": "3", n" + " "name": ""n" + " }n" + " ]n" + "}"; JSONObject json = bject(jsonString); doPostFileStreamAndJsonObj(url, fileList, json); }因为是流的⽅式,所以要从http请求⾥获取body,然后再解析接收⽅:@RestController@RequestMapping("/test")//跨域注解@CrossOriginpublic class TestController { /** * 接收流信息 * * @param request * @return */ @PostMapping("/receiveStream") public String receiveStream(HttpServletRequest request) { String result = ""; n("进来了"); try { //获取request⾥的所有部分 Collection parts = ts(); for (Iterator iterator = or(); t(); ) { Part part = (); n("名称========" + e()); if ("JsonObj".equals(e())) { //解析json对象 BufferedReader reader = new BufferedReader(new InputStreamReader(utStream())); String line = ""; String parseString = ""; while ((line = ne()) != null) { parseString += line; } JSONObject json = bject(parseString); n("接收到的json对象为=====" + String()); } else if ("File".equals(e())) { String fileName = ""; Long size = e(); //⽂件名的获取,可以直接获取header⾥定义好的FIleName(⼤部分没有),或从Content-Disposition去剪切出来// String head = der("Content-Disposition");// fileName = ing(f("filename=")+ 10, dexOf(""")); fileName = der("FileName"); n(fileName + size);// //这⾥就是⽂件,⽂件流就可以直接写⼊到⽂件了// InputStream inputStream = utStream();// OutputStream outputStream = new FileOutputStream(fileName);// int bytesWritten = 0;// int byteCount = 0;// byte[] bytes = new byte[1024];// while ((byteCount = (bytes)) != -1) {// (bytes, bytesWritten, byteCount);// bytesWritten += byteCount;// }// ();// (); } } //如果嫌上⾯获取⽂件的⿇烦,⽤下⾯这个⽐较简单,解析成multipartFile MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //统计⽂件数 Integer fileCount = 0; //请求⾥key为File的元素(即⽂件元素) List list = es("File"); while (fileCount < ()) { MultipartFile file = (fileCount); n(e()); n(ginalFilename()); n(e()); fileCount++; } n("共有" + fileCount + "个⽂件"); } catch (Exception e) { tackTrace(); } return result; }}控制台输出: 流的⽅式到这⾥就结束了,httpclient的⽅式稍后再写如果模拟的时候有相关参数不了解,可以浏览器打开随便⼀个⽹页,f12看看传的参数都有哪些,例如:欢迎留⾔指正
2023年8月1日发(作者:)
java模拟http请求,通过流的⽅式发送数据,模拟接收流⽂件和json数据项⽬⾥碰到过模拟ajax请求的案例,研究了⼀下,觉得 httpClient 是真⼼好⽤,由于模拟环境搞了⼤半天,httpclient就另外再写博⽂吧下⾯的例⼦介绍流的⽅式发送和接收,这个就有点暴⼒了,想传啥都⾏:以字节流的⽅式发送数据(可以是任何数据)看标题就知道了,简单粗暴的⽅法,管他什么格式,统统“流”过去,不过既然是模拟的,要配置好其他参数,对⽅才能正常接收到发送⽅: /** * 以流的⽅式 * 发送⽂件和json对象 * * @return */ public static String doPostFileStreamAndJsonObj(String url, List fileList, JSONObject json) { String result = "";//请求返回参数 String jsonString = String();//获得jsonstirng,或者toString都可以,只要是json格式,给了别⼈能解析成json就⾏// n("================");// n(xml);//可以打印出来瞅瞅// n("================"); try { //开始设置模拟请求的参数,额,不⼀个个介绍了,根据需要拿 String boundary = "------WebKitFormBoundaryUey8ljRiiZqhZHBu"; URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) nnection(); utput(true); nput(true); Caches(false); uestMethod("POST"); uestProperty("connection", "Keep-Alive"); //这⾥模拟的是⽕狐浏览器,具体的可以f12看看请求的user-agent是什么 uestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); uestProperty("Charsert", "UTF-8"); //这⾥的content-type要设置成表单格式,模拟ajax的表单请求 uestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); // 指定流的⼤⼩,当内容达到这个值的时候就把流输出 nkedStreamingMode(10240000); //定义输出流,有什么数据要发送的,直接后⾯append就可以,记得转成byte再append OutputStream out = new DataOutputStream(putStream()); byte[] end_data = ("rn--" + boundary + "--rn").getBytes();// 定义最后数据分隔线 StringBuilder sb = new StringBuilder(); //添加form属性 ("--"); (boundary); ("rn"); //这⾥存放要传输的参数,name = xml ("Content-Disposition: form-data; name="JsonObj""); ("rnrn"); //把要传的json字符串放进来 (jsonString); (ng().getBytes("utf-8")); ("rn".getBytes("utf-8")); int leng = (); for (int i = 0; i < leng; i++) { File file = new File((i)); if(()){ sb = new StringBuilder(); ("--"); ("--"); (boundary); ("rn"); //这⾥的参数啥的是我项⽬⾥对⽅接收要⽤到的,具体的看你的项⽬怎样的格式 ("Content-Disposition: form-data;name="File" + "";filename="" + e() + ""rn"); //这⾥拼接个fileName,⽅便后⾯⽤第⼀种⽅式接收(如果是纯⽂件,不带其他参数,就可以不⽤这个了,因为Multipart可以直接解析⽂件) ("FileName:"+ e() + "rn"); //发送⽂件是以流的⽅式发送,所以这⾥的content-type是octet-stream流 ("Content-Type:application/octet-streamrnrn"); byte[] data = ng().getBytes(); (data); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = (bufferOut)) != -1) { (bufferOut, 0, bytes); } int j = i + 1; if (leng > 1 && j != leng) { ("rn".getBytes()); // 多个⽂件时,⼆个⽂件之间加⼊这个 } (); }else{ n("没有发现⽂件"); } } //发送流 (end_data); (); (); // 定义BufferedReader输⼊流来读取URL的响应 BufferedReader reader = new BufferedReader(new InputStreamReader( utStream())); String line = ""; while ((line = ne()) != null) { result += line; }// n("================");// n(ng());//可以把结果打印出来瞅瞅// n("================"); //后⾯可以对结果进⾏解析(如果返回的是格式化的数据的话) } catch (Exception e) { n("发送POST请求出现异常!" + e); tackTrace(); } return result; } public static void main(String args[]) throws Exception { //模拟流⽂件及参数上传 String url = "127.0.0.1:8090/kty/test/receiveStream"; //⽂件列表,搞了三个本地⽂件 List fileList = new ArrayList<>(); ("F:mephotos动漫"); ("F:mephotos动漫"); ("F:mephotos动漫"); //json字符串,模拟了⼀个,传图⽚名字吧 String jsonString = "{n" + " "token": "stream data", n" + " "content": [n" + " {n" + " "id": "1", n" + " "name": ""n" + " }, n" + " {n" + " "id": "2", n" + " "name": ""n" + " }, n" + " {n" + " "id": "3", n" + " "name": ""n" + " }n" + " ]n" + "}"; JSONObject json = bject(jsonString); doPostFileStreamAndJsonObj(url, fileList, json); }因为是流的⽅式,所以要从http请求⾥获取body,然后再解析接收⽅:@RestController@RequestMapping("/test")//跨域注解@CrossOriginpublic class TestController { /** * 接收流信息 * * @param request * @return */ @PostMapping("/receiveStream") public String receiveStream(HttpServletRequest request) { String result = ""; n("进来了"); try { //获取request⾥的所有部分 Collection parts = ts(); for (Iterator iterator = or(); t(); ) { Part part = (); n("名称========" + e()); if ("JsonObj".equals(e())) { //解析json对象 BufferedReader reader = new BufferedReader(new InputStreamReader(utStream())); String line = ""; String parseString = ""; while ((line = ne()) != null) { parseString += line; } JSONObject json = bject(parseString); n("接收到的json对象为=====" + String()); } else if ("File".equals(e())) { String fileName = ""; Long size = e(); //⽂件名的获取,可以直接获取header⾥定义好的FIleName(⼤部分没有),或从Content-Disposition去剪切出来// String head = der("Content-Disposition");// fileName = ing(f("filename=")+ 10, dexOf(""")); fileName = der("FileName"); n(fileName + size);// //这⾥就是⽂件,⽂件流就可以直接写⼊到⽂件了// InputStream inputStream = utStream();// OutputStream outputStream = new FileOutputStream(fileName);// int bytesWritten = 0;// int byteCount = 0;// byte[] bytes = new byte[1024];// while ((byteCount = (bytes)) != -1) {// (bytes, bytesWritten, byteCount);// bytesWritten += byteCount;// }// ();// (); } } //如果嫌上⾯获取⽂件的⿇烦,⽤下⾯这个⽐较简单,解析成multipartFile MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //统计⽂件数 Integer fileCount = 0; //请求⾥key为File的元素(即⽂件元素) List list = es("File"); while (fileCount < ()) { MultipartFile file = (fileCount); n(e()); n(ginalFilename()); n(e()); fileCount++; } n("共有" + fileCount + "个⽂件"); } catch (Exception e) { tackTrace(); } return result; }}控制台输出: 流的⽅式到这⾥就结束了,httpclient的⽅式稍后再写如果模拟的时候有相关参数不了解,可以浏览器打开随便⼀个⽹页,f12看看传的参数都有哪些,例如:欢迎留⾔指正
发布评论