import java.io.*;import java.net.*;public classFileUpload {/*** 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应
*@paramurl 请求地址 form表单url地址
*@paramfilePath 文件在服务器保存路径
*@returnString url的响应信息返回值
*@throwsIOException*/
public String send(String url, String filePath) throwsIOException {
String result= null;
File file= newFile(filePath);if (!file.exists() || !file.isFile()) {throw new IOException("文件不存在");
}/*** 第一部分*/URL urlObj= newURL(url);//连接
HttpURLConnection con =(HttpURLConnection) urlObj.openConnection();/*** 设置关键值*/con.setRequestMethod("POST"); //请求方式
con.setDoInput(true);
con.setDoOutput(true); //当为post方式时,需要设置,因为要输入数据流
con.setUseCaches(false); //post方式不能使用缓存//设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");//设置边界
String BOUNDARY = "----------" +System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+BOUNDARY);//请求正文信息//需要提交的文件
StringBuilder sb = newStringBuilder();
sb.append("--"+BOUNDARY+"\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");byte[] head = sb.toString().getBytes("utf-8");//获得输出流
OutputStream out = newDataOutputStream(con.getOutputStream());//输出表头
out.write(head);//文件正文部分//把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(newFileInputStream(file));int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut,0, bytes);
}
in.close();//需要提交的普通表单数据
sb = newStringBuilder();
sb.append("\r\n--"+BOUNDARY+"\r\n");
sb.append("Content-Disposition: form-data;name=\"type\"\r\n\r\n");//注意:在设置数据头 与 数据内容是 中间是隔了一行
sb.append("1\r\n");
sb.append("--"+BOUNDARY+"\r\n");
sb.append("Content-Disposition: form-data;name=\"wxroleid\"\r\n\r\n");
sb.append("201\r\n");
head= sb.toString().getBytes("utf-8");
out.write(head);//结尾部分
byte[] foot = ("--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
StringBuffer buffer= newStringBuffer();
BufferedReader reader= null;try{//定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(newInputStreamReader(con.getInputStream()));
String line= null;while ((line = reader.readLine()) != null) {//System.out.println(line);
buffer.append(line);
}if(result==null){
result=buffer.toString();
}
}catch(IOException e) {
System.out.println("发送POST请求出现异常!" +e);
e.printStackTrace();throw new IOException("数据读取异常");
}finally{if(reader!=null){
reader.close();
}
}returnresult;
}//测试使用
public static void main(String[] args) throwsIOException {
String filePath= "需要上传的文件路径"; // 如d:/test.pdf
String sendUrl= "http://192.168.0.125:8080/dataProvider/uploadReport";
String result= null;
FileUpload fileUpload= newFileUpload();
result=fileUpload.send(sendUrl, filePath);
System.out.println(result);
}
}