java模拟http请求,通过流(stream)的⽅式,发送json数据和⽂
件
发送端:
/**
* 以流的⽅式
* 发送⽂件和json对象
*
* @return
*/
public static String doPostFileStreamAndJsonObj(String url, List<String> fileList, JSONObject json) {
String result = "";//请求返回参数
String jsonString = JSONString();//获得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 OutputStream());
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.String().getBytes("utf-8"));
out.write("\r\n".getBytes("utf-8"));
int leng = fileList.size();
for (int i = 0; i < leng; i++) {
File file = new (i));
ists()){
sb = new StringBuilder();
sb.append("--");
sb.append(boundary);
sb.append("\r\n");
/
/这⾥的参数啥的是我项⽬⾥对⽅接收要⽤到的,具体的看你的项⽬怎样的格式
sb.append("Content-Disposition: form-data;name=\"File"
+ "\";filename=\"" + Name() + "\"\r\n");
//这⾥拼接个fileName,⽅便后⾯⽤第⼀种⽅式接收(如果是纯⽂件,不带其他参数,就可以不⽤这个了,因为Multipart可以直接解析⽂件)
sb.append("FileName:"+ Name() + "\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( InputStream()));
String line = "";
while ((line = adLine()) != null) {
result += line;
}
/
/ System.out.println("================");
// System.out.String());//可以把结果打印出来瞅瞅
// 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 = "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);
}
-----------------------------------------
接收端:
@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 = Parts();
for (Iterator<Part> iterator = parts.iterator(); iterator.hasNext(); ) {
Part part = ();
System.out.println("名称========" + Name());
if ("JsonObj".Name())) {
//解析json对象
BufferedReader reader = new BufferedReader(new InputStream()));
String line = "";
String parseString = "";
while ((line = adLine()) != null) {
parseString += line;
}
JSONObject json = JSONObject.parseObject(parseString);
System.out.println("接收到的json对象为=====" + JSONString());
} else if ("File".Name())) {
String fileName = "";
Long size = Size();
//⽂件名的获取,可以直接获取header⾥定义好的FIleName(⼤部分没有),或从Content-Disposition去剪切出来// String head = Header("Content-Disposition");
// fileName = head.substring(head.indexOf("filename=")+ 10, head.lastIndexOf("\""));
fileName = Header("FileName");
System.out.println(fileName + size);
// //这⾥就是⽂件,⽂件流就可以直接写⼊到⽂件了
// InputStream inputStream = InputStream();
// OutputStream outputStream = new FileOutputStream(fileName);
// int bytesWritten = 0;
// int byteCount = 0;
// byte[] bytes = new byte[1024];
// while ((byteCount = ad(bytes)) != -1) {
// outputStream.write(bytes, bytesWritten, byteCount);
// bytesWritten += byteCount;
浏览器json格式化/
/ }
// inputStream.close();
// outputStream.close();
}
}
//如果嫌上⾯获取⽂件的⿇烦,⽤下⾯这个⽐较简单,解析成multipartFile MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //统计⽂件数
Integer fileCount = 0;
//请求⾥key为File的元素(即⽂件元素)
List<MultipartFile> list = Files("File");
while (fileCount < list.size()) {
MultipartFile file = (fileCount);
System.out.Name());
System.out.OriginalFilename());
System.out.Size());
fileCount++;
}
System.out.println("共有" + fileCount + "个⽂件");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论