普通上传文件以下代码就够用了:
/**
* 上传文件
* @param urlStr
* @param file
*/
public static String upload(String urlStr, File file, String fileName){
String rv = "";
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String boundary = "----aryg4pBUG8gGY9qgAAs";
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream out = new DataOutputStream(conn.getOutputStream());
StringBuilder sb = new StringBuilder();
sb.append("--"+boundary);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filename=\""+ fileName + "\"\r\n");
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);
}
out.write("\r\n".getBytes());
in.close();
//结束分割符
byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sbf = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sbf.append(line);
}
rv = sbf.toString();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return rv;
}
但是如果上面的方式上传不了,返回400,那么就需要使用工具。
典型应用是:SpringMVC中的文件上传就不能用上面的代码,只能使用工具才行。
xUtils是一个github开源项目,封装了发送http请求的细节,也就是干了浏览器发送http请求干的事情。