http post 上传文件

ymjavasoft 2012-11-14 11:07:42

List<String> list = new ArrayList<String>();
list.add("d:\\test.doc");
String BOUNDARY = "A300x"; // 定义数据分隔线
URL urls = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
int leng = list.size();
for(int i=0;i<leng;i++){
String fname = list.get(i);
File file = new File(fname);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition:name=\"file\";filename=\""+ URLEncoder.encode(file.getName(), "UTF-8") +"\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
sb.append("--"+BOUNDARY+"--");
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()); //多个文件时,二个文件之间加入这个
System.out.println(sb.toString());
in.close();
}
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

--------------------------------------------------
报错

{"error":
{"code":"request_body_invalid",
"message":"The provided request entity body has invalid value for the 'Content-Disposition' header.
Expected format is 'Content-Disposition: form-data;name="file";filename="[FileName]"'."
}
}
-----------------------------------------------------
官方API提供格式
POST https://apis.live.net/v5.0/me/skydrive/files?access_token=ACCESS_TOKEN

Content-Type: multipart/form-data; boundary=A300x

--A300x
Content-Disposition: form-data; name="file"; filename="HelloWorld.txt"
Content-Type: application/octet-stream

Hello, World!
--A300x--

---------------------------
为什么报错啊,我是这样写的呢。求大神帮忙看看啊
...全文
81 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧