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

发送端:

/**
* 以流的方式
* 发送文件和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);
}

 

 

-----------------------------------------

接收端:


@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;
}
}

posted @ 2019-12-05 15:59  IT小白6270  阅读(8705)  评论(0编辑  收藏  举报