① 微信開發平台中有個介面是上傳多媒體文件,我用的是java 開發的,我怎麼樣才能在後台實現呢代碼如下:
/**
*文件上傳到微信伺服器
*@paramfileType文件類型
*@paramfilePath文件路徑
*@returnjsONObject
*@throwsException
*/
publicstaticJSONObjectsend(StringfileType,StringfilePath)throwsException{
Stringresult=null;
Filefile=newFile(filePath);
if(!file.exists()||!file.isFile()){
thrownewIOException("文件不存在");
}
/**
*第一部分
*/
URLurlObj=newURL("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+getAccess_token()+"&type="+fileType+"");
HttpURLConnectioncon=(HttpURLConnection)urlObj.openConnection();
con.setRequestMethod("POST");//以Post方式提交表單,默認get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);//post方式不能使用緩存
//設置請求頭信息
con.setRequestProperty("Connection","Keep-Alive");
con.setRequestProperty("Charset","UTF-8");
//設置邊界
StringBOUNDARY="----------"+System.currentTimeMillis();
con.setRequestProperty("Content-Type","multipart/form-data;boundary="+BOUNDARY);
//請求正文信息
//第一部分:
StringBuildersb=newStringBuilder();
sb.append("--");//必須多兩道線
sb.append(BOUNDARY);
sb.append(" ");
sb.append("Content-Disposition:form-data;name="file";filename=""+file.getName()+"" ");
sb.append("Content-Type:application/octet-stream ");
byte[]head=sb.toString().getBytes("utf-8");
//獲得輸出流
OutputStreamout=newDataOutputStream(con.getOutputStream());
//輸出表頭
out.write(head);
//文件正文部分
//把文件已流文件的方式推入到url中
DataInputStreamin=newDataInputStream(newFileInputStream(file));
intbytes=0;
byte[]bufferOut=newbyte[1024];
while((bytes=in.read(bufferOut))!=-1){
out.write(bufferOut,0,bytes);
}
in.close();
//結尾部分
byte[]foot=(" --"+BOUNDARY+"-- ").getBytes("utf-8");//定義最後數據分隔線
out.write(foot);
out.flush();
out.close();
StringBufferbuffer=newStringBuffer();
BufferedReaderreader=null;
try{
//定義BufferedReader輸入流來讀取URL的響應
reader=newBufferedReader(newInputStreamReader(con.getInputStream()));
Stringline=null;
while((line=reader.readLine())!=null){
//System.out.println(line);
buffer.append(line);
}
if(result==null){
result=buffer.toString();
}
}catch(IOExceptione){
System.out.println("發送POST請求出現異常!"+e);
e.printStackTrace();
thrownewIOException("數據讀取異常");
}finally{
if(reader!=null){
reader.close();
}
}
JSONObjectjsonObj=newJSONObject(result);
returnjsonObj;
}