【移動應(yīng)用開發(fā)技術(shù)】java微信開發(fā)之上傳下載多媒體文件的示例_第1頁
【移動應(yīng)用開發(fā)技術(shù)】java微信開發(fā)之上傳下載多媒體文件的示例_第2頁
【移動應(yīng)用開發(fā)技術(shù)】java微信開發(fā)之上傳下載多媒體文件的示例_第3頁
【移動應(yīng)用開發(fā)技術(shù)】java微信開發(fā)之上傳下載多媒體文件的示例_第4頁
【移動應(yīng)用開發(fā)技術(shù)】java微信開發(fā)之上傳下載多媒體文件的示例_第5頁
已閱讀5頁,還剩10頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

【移動應(yīng)用開發(fā)技術(shù)】java微信開發(fā)之上傳下載多媒體文件的示例

這篇文章將為大家詳細講解有關(guān)java微信開發(fā)之上傳下載多媒體文件的示例,在下覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲?;貜?fù)圖片、音頻、視頻消息都是需要media_id的,這個是需要將多媒體文件上傳到微信服務(wù)器才有的。上傳下載多媒體文件的方法還是寫到WeixinUtil.java中。代碼如下:import

java.io.BufferedOutputStream;

import

java.io.BufferedReader;

import

java.io.DataInputStream;

import

java.io.DataOutputStream;

import

java.io.File;

import

java.io.FileInputStream;

import

java.io.FileOutputStream;

import

java.io.IOException;

import

java.io.InputStream;

import

java.io.InputStreamReader;

import

java.io.OutputStream;

import

.HttpURLConnection;

import

.MalformedURLException;

import

.URL;

import

java.security.KeyManagementException;

import

java.security.NoSuchAlgorithmException;

import

java.security.NoSuchProviderException;

import

java.security.SecureRandom;

import

java.util.Calendar;

import

java.util.Date;

import

java.util.HashMap;

import

java.util.Map;

import

.ssl.HttpsURLConnection;

import

.ssl.SSLContext;

import

.ssl.SSLSocketFactory;

import

.ssl.TrustManager;

import

net.sf.json.JSONObject;

import

mons.lang.StringUtils;

import

org.apache.log4j.Logger;

import

ject.model.menu.AccessToken;

import

ject.model.menu.Menu;

public

class

WeixinUtil

{

private

static

Logger

log

=

Logger.getLogger(WeixinUtil.class);

public

final

static

String

APPID

=

"wxb927d4280e6db674";

public

final

static

String

APP_SECRET

=

"21441e9f3226eee81e14380a768b6d1e";

//

獲取access_token的接口地址(GET)

限200(次/天)

public

final

static

String

access_token_url

=

"/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

//

創(chuàng)建菜單

public

final

static

String

create_menu_url

=

"/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

//

存放:1.token,2:獲取token的時間,3.過期時間

public

final

static

Map<String,Object>

accessTokenMap

=

new

HashMap<String,Object>();

/**

*

發(fā)起https請求并獲取結(jié)果

*

*

@param

requestUrl

請求地址

*

@param

requestMethod

請求方式(GET、POST)

*

@param

outputStr

提交的數(shù)據(jù)

*

@return

JSONObject(通過JSONObject.get(key)的方式獲取json對象的屬性值)

*/

public

static

JSONObject

handleRequest(String

requestUrl,String

requestMethod,String

outputStr)

{

JSONObject

jsonObject

=

null;

try

{

URL

url

=

new

URL(requestUrl);

HttpsURLConnection

conn

=

(HttpsURLConnection)

url.openConnection();

SSLContext

ctx

=

SSLContext.getInstance("SSL",

"SunJSSE");

TrustManager[]

tm

=

{new

MyX509TrustManager()};

ctx.init(null,

tm,

new

SecureRandom());

SSLSocketFactory

sf

=

ctx.getSocketFactory();

conn.setSSLSocketFactory(sf);

conn.setDoInput(true);

conn.setDoOutput(true);

conn.setRequestMethod(requestMethod);

conn.setUseCaches(false);

if

("GET".equalsIgnoreCase(requestMethod))

{

conn.connect();

}

if

(StringUtils.isNotEmpty(outputStr))

{

OutputStream

out

=

conn.getOutputStream();

out.write(outputStr.getBytes("utf-8"));

out.close();

}

InputStream

in

=

conn.getInputStream();

BufferedReader

br

=

new

BufferedReader(new

InputStreamReader(in,"utf-8"));

StringBuffer

buffer

=

new

StringBuffer();

String

line

=

null;

while

((line

=

br.readLine())

!=

null)

{

buffer.append(line);

}

in.close();

conn.disconnect();

jsonObject

=

JSONObject.fromObject(buffer.toString());

}

catch

(MalformedURLException

e)

{

e.printStackTrace();

log.error("URL錯誤!");

}

catch

(IOException

e)

{

e.printStackTrace();

}

catch

(NoSuchAlgorithmException

e)

{

e.printStackTrace();

}

catch

(NoSuchProviderException

e)

{

e.printStackTrace();

}

catch

(KeyManagementException

e)

{

e.printStackTrace();

}

return

jsonObject;

}

/**

*

獲取access_token

*

*

@author

qincd

*

@date

Nov

6,

2014

9:56:43

AM

*/

public

static

AccessToken

getAccessToken(String

appid,String

appSecret)

{

AccessToken

at

=

new

AccessToken();

//

每次獲取access_token時,先從accessTokenMap獲取,如果過期了就重新從微信獲取

//

沒有過期直接返回

//

從微信獲取的token的有效期為2個小時

if

(!accessTokenMap.isEmpty())

{

Date

getTokenTime

=

(Date)

accessTokenMap.get("getTokenTime");

Calendar

c

=

Calendar.getInstance();

c.setTime(getTokenTime);

c.add(Calendar.HOUR_OF_DAY,

2);

getTokenTime

=

c.getTime();

if

(getTokenTime.after(new

Date()))

{

("緩存中發(fā)現(xiàn)token未過期,直接從緩存中獲取access_token");

//

token未過期,直接從緩存獲取返回

String

token

=

(String)

accessTokenMap.get("token");

Integer

expire

=

(Integer)

accessTokenMap.get("expire");

at.setToken(token);

at.setExpiresIn(expire);

return

at;

}

}

String

requestUrl

=

access_token_url.replace("APPID",

appid).replace("APPSECRET",

appSecret);

JSONObject

object

=

handleRequest(requestUrl,

"GET",

null);

String

access_token

=

object.getString("access_token");

int

expires_in

=

object.getInt("expires_in");

("\naccess_token:"

+

access_token);

("\nexpires_in:"

+

expires_in);

at.setToken(access_token);

at.setExpiresIn(expires_in);

//

每次獲取access_token后,存入accessTokenMap

//

下次獲取時,如果沒有過期直接從accessTokenMap取。

accessTokenMap.put("getTokenTime",

new

Date());

accessTokenMap.put("token",

access_token);

accessTokenMap.put("expire",

expires_in);

return

at;

}

/**

*

創(chuàng)建菜單

*

*

@author

qincd

*

@date

Nov

6,

2014

9:56:36

AM

*/

public

static

boolean

createMenu(Menu

menu,String

accessToken)

{

String

requestUrl

=

create_menu_url.replace("ACCESS_TOKEN",

accessToken);

String

menuJsonString

=

JSONObject.fromObject(menu).toString();

JSONObject

jsonObject

=

handleRequest(requestUrl,

"POST",

menuJsonString);

String

errorCode

=

jsonObject.getString("errcode");

if

(!"0".equals(errorCode))

{

log.error(String.format("菜單創(chuàng)建失??!errorCode:%d,errorMsg:%s",jsonObject.getInt("errcode"),jsonObject.getString("errmsg")));

return

false;

}

("菜單創(chuàng)建成功!");

return

true;

}

//

上傳多媒體文件到微信服務(wù)器

public

static

final

String

upload_media_url

=

"/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";

/**

*

上傳多媒體文件到微信服務(wù)器<br>

*

@see

/code/snippet_1029535_23824

*

@see

/wiki/index.php?title=上傳下載多媒體文件

*

*

@author

qincd

*

@date

Nov

6,

2014

4:11:22

PM

*/

public

static

JSONObject

uploadMediaToWX(String

filePath,String

type,String

accessToken)

throws

IOException{

File

file

=

new

File(filePath);

if

(!file.exists())

{

log.error("文件不存在!");

return

null;

}

String

url

=

upload_media_url.replace("ACCESS_TOKEN",

accessToken).replace("TYPE",

type);

URL

urlObj

=

new

URL(url);

HttpURLConnection

conn

=

(HttpURLConnection)

urlObj.openConnection();

conn.setDoInput(true);

conn.setDoOutput(true);

conn.setUseCaches(false);

conn.setRequestProperty("Connection",

"Keep-Alive");

conn.setRequestProperty("Charset",

"UTF-8");

//

設(shè)置邊界

String

BOUNDARY

=

""

+

System.currentTimeMillis();

conn.setRequestProperty("Content-Type",

"multipart/form-data;

boundary="

+

BOUNDARY);

//

請求正文信息

//

第一部分:

StringBuilder

sb

=

new

StringBuilder();

sb.append("--");

//

////////必須多兩道線

sb.append(BOUNDARY);

sb.append("\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

=

new

DataOutputStream(conn.getOutputStream());

out.write(head);

//

文件正文部分

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);

}

in.close();

//

結(jié)尾部分

byte[]

foot

=

("\r\n--"

+

BOUNDARY

+

"--\r\n").getBytes("utf-8");//

定義最后數(shù)據(jù)分隔線

out.write(foot);

out.flush();

out.close();

/**

*

讀取服務(wù)器響應(yīng),必須讀取,否則提交不成功

*/

try

{

//

定義BufferedReader輸入流來讀取URL的響應(yīng)

StringBuffer

buffer

=

new

StringBuffer();

BufferedReader

reader

=

new

BufferedReader(new

InputStreamReader(

conn.getInputStream()));

String

line

=

null;

while

((line

=

reader.readLine())

!=

null)

{

buffer.append(line);

}

reader.close();

conn.disconnect();

return

JSONObject.fromObject(buffer.toString());

}

catch

(Exception

e)

{

log.error("發(fā)送POST請求出現(xiàn)異常!"

+

e);

e.printStackTrace();

}

return

null;

}

public

static

final

String

download_media_url

=

"/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";

/**

*

從微信服務(wù)器下載多媒體文件

*

*

@author

qincd

*

@date

Nov

6,

2014

4:32:12

PM

*/

public

static

String

downloadMediaFromWx(String

accessToken,String

mediaId,String

fileSavePath)

throws

IOException

{

if

(StringUtils.isEmpty(accessToken)

||

StringUtils.isEmpty(mediaId))

return

null;

String

requestUrl

=

download_media_url.replace("ACCESS_TOKEN",

accessToken).replace("MEDIA_ID",

mediaId);

URL

url

=

new

URL(requestUrl);

HttpURLConnection

conn

=

(HttpURLConnection)

url.openConnection();

conn.setRequestMethod("GET");

conn.setDoInput(true);

conn.setDoOutput(true);

InputStream

in

=

conn.getInputStream();

File

dir

=

new

File(fileSavePath);

if

(!dir.exists())

{

dir.mkdirs();

}

if

(!fileSavePath.endsWith("/"))

{

fileSavePath

+=

"/";

}

String

ContentDisposition

=

conn.getHeaderField("Content-disposition");

String

weixinServerFileName

=

ContentDisposition.substring(ContentDisposition.indexOf("filename")+10,

ContentDisposition.length()

-1);

fileSavePath

+=

weixinServerFileName;

BufferedOutputStream

bos

=

new

BufferedOutputStream(new

FileOutputStream(fileSavePath));

byte[]

data

=

new

byte[1024];

int

len

=

-1;

while

((len

=

in.read(data))

!=

-1)

{

bos.write(data,0,len);

}

bos.close();

in.close();

conn.disconnect();

return

fileSavePath;

}

}測試代碼:public

class

WeixinUtilTest

{

/**

*

*

@author

qincd

*

@date

Nov

6,

2014

9:57:54

AM

*/

public

static

void

main(String[]

args)

{

//

1).獲取access_token

AccessToken

accessToken

=

WeixinUtil.getAccessToken(WeixinUtil.APPID,

WeixinUtil.APP_SECRET);

String

filePath

=

"C:\\Users\\qince\\Pictures\\壁紙20141029091612.jpg";

JSONObject

uploadJsonObj

=

testUploadMedia(filePath,"image",accessToken.getToken());

if

(uploadJsonObj

==

null)

{

System.out.println("上傳圖片失敗");

return;

}

int

errcode

=

0;

if

(uploadJsonObj.containsKey("errcode"))

{

errcode

=

uploadJsonObj.getInt("errcode");

}

if

(errcode

==

0)

{

System.out.println("圖片上傳成功");

String

mediaId

=

uploadJsonObj.getString("media_id");

long

createAt

=

uploadJsonObj.getLong("created_at");

System.out.println("--Details:");

System.out.println("media_id:"

+

mediaId);

System.out.println("created_at:"

+

createAt);

}

else

{

Sys

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論