为什么我自己写的upload方法不能用
//获取mediaid,上传文件到微信客户端
public static String getMediaId(String filePath,String accessToken,String type) throws Exception {
File file = new File(filePath);
if(!file.exists()){
throw new IOException("文件不存在哦");
}
String url = UPLOAD_URL.replace("ACCESS_TOKEN",accessToken).replace("TYPE",type);
URL urlObject = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObject.openConnection();
//设置连接信息
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
//设置请求头信息
con.setRequestProperty("Connection","Keep-Alive");
con.setRequestProperty("Charset","UTF-8");
//设置边界
String BOUNDARY = "----------"+System.currentTimeMillis();
con.setRequestProperty("Content-Type","mutipart/form-data;boundary="+BOUNDARY);
//设置请求体的头部
/*
-----------------------------7e15d2960544
Content-Disposition: form-data; name="file"; filename="C:\Users\admin\Desktop\hello.txt"
Content-Type: text/plain
hello
-----------------------------7e15d2960544--
*/
//将请求体的头部信息写入con获取的outStream中
StringBuffer sb =new StringBuffer();
sb.append("--");
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");
System.out.println("文件的请求头部信息是:");
System.out.println(sb.toString());
byte[] requestHead = sb.toString().getBytes("UTF-8");
//获取输入流
OutputStream out = new DataOutputStream(con.getOutputStream());
//写入请求头的一些基本信息
out.write(requestHead);
//处理文件正文部分
DataInputStream in = new DataInputStream(new FileInputStream(file));
byte[] b = new byte[1024];
int n;
while((n=in.read(b))!=-1){
System.out.println(n);
out.write(b,0,n);
}
in.close();
//处理结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
System.out.println("\r\n--" + BOUNDARY + "--\r\n");
out.write(foot);
out.flush();
out.close();
//开始读取微信客户端返回的数据
StringBuffer buffer = new StringBuffer();;
BufferedReader br = null;
String result = null;
try {
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line ;
while((line = br.readLine())!=null){
buffer.append(line);
}
if(result ==null){
result = buffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
}
//解析返回的String数据
JSONObject jsonObject = JSONObject.fromObject(result);
System.out.println(jsonObject);
String mediaId = jsonObject.getString("media_id");
return mediaId;
}
结果:
Exception in thread "main" net.sf.json.JSONException: JSONObject["media_id"] not found.
{"errcode":41005,"errmsg":"media data missing hint: [bS31uA0672e565]"}
at net.sf.json.JSONObject.getString(JSONObject.java:2245)
at utils.InterfaceUtils.getMediaId(InterfaceUtils.java:139)
at utils.InterfaceUtils.main(InterfaceUtils.java:144)
这个文件我用OutputStream os = new FileOutputStream()是可以获取到的,可是就是不行。。。