代码示例
更新时间:2022-12-01
代码示例
示例代码以 Java 语言为例讲解美图 APP 的实现,代码分为 APP 客户端和应用服务器端两部分。
APP 客户端代码样例
APP 端代码主要包括 BOSClient 初始化、从 APP Server 端获取 BOS 信息、及上传文件到 BOS 三个功能模块。
BOSClient 初始化
Plain Text
1public class bos {
2 private string ak = null;
3 private string sk = null;
4 private string endpoint = null;
5 private string ststoken = null;
6 private bosclient client = null;
7
8 public bos(string ak, string sk, string endpoint, string ststoken) {
9 this.ak = ak;
10 this.sk = sk;
11 this.endpoint = endpoint;
12 this.ststoken = ststoken;
13 client = createclient();
14 }
15
16 public bosclient createclient() {
17 bosclientconfiguration config = new bosclientconfiguration();
18 bcecredentials credentials = null;
19 if (ststoken != null && !ststoken.equalsignorecase("")) {
20 credentials = new defaultbcesessioncredentials(ak, sk, ststoken);
21 } else {
22 credentials = new defaultbcecredentials(ak, sk);
23 }
24 config.setendpoint(endpoint);
25 config.setcredentials(credentials);
26 return new bosclient(config);
27 }
28
29 public void uploadfile(string bucket, string object, file file) {
30 client.putobject(bucket, object, file);
31 }
32
33 public void uploadfile(string bucket, string object, inputstream inputstream) {
34 client.putobject(bucket, object, inputstream);
35 }
36
37 public void uploadfile(string bucket, string object, byte[] data) {
38 client.putobject(bucket, object, data);
39 }
40
41 public byte[] downloadfilecontent(string bucket, string object) {
42 return client.getobjectcontent(bucket, object);
43 }
44}
上传文件到 BOS 代码实现
Plain Text
1public void uploadPicToBos() {
2 // 1. get pic params from ui: file name, file location uri etc
3 // 2. send params to app server and get sts, bucket name and region
4 // 3. upload selected pic to bos with sts etc, which bos client needs
5
6 EditText et = (EditText) findViewById(R.id.app_server_addr_edittext);
7 final String appServerAddr = et.getText().toString();
8
9 new Thread(new Runnable() {
10 @Override
11 public void run() {
12 Map<String, Object> bosInfo = AppServer.getBosInfoFromAppServer(appServerAddr, "user-demo",
13 AppServer.BosOperationType.UPLOAD);
14
15 if (bosInfo == null) {
16 return;
17 }
18 showToast(bosInfo.toString(), Toast.LENGTH_LONG);
19
20 String ak = (String) bosInfo.get("ak");
21 String sk = (String) bosInfo.get("sk");
22 String stsToken = (String) bosInfo.get("stsToken");
23 String endpoint = (String) bosInfo.get("endpoint");
24 String bucketName = (String) bosInfo.get("bucketName");
25 String objectName = (String) bosInfo.get("objectName");
26 String prefix = (String) bosInfo.get("prefix");
27 Log.i("UploadFileToBos", bosInfo.toString());
28
29 // specify a object name if the app server does not specify one
30 if (objectName == null || objectName.equalsIgnoreCase("")) {
31 objectName = ((EditText) findViewById(R.id.bos_object_name_edittext)).getText().toString();
32 if (prefix != null && !prefix.equalsIgnoreCase("")) {
33 objectName = prefix + "/" + objectName;
34 }
35 }
36
37 Bos bos = new Bos(ak, sk, endpoint, stsToken);
38 try {
39 byte[] data = Utils.readAllFromStream(MainActivity.this.getContentResolver().openInputStream(selectedPicUri));
40 bos.uploadFile(bucketName, objectName, data);
41 } catch (Throwable e) {
42 Log.e("MainActivity/Upload", "Failed to upload file to bos: " + e.getMessage());
43 showToast("Failed to upload file: " + e.getMessage());
44 return;
45 }
46 // finished uploading file, send a message to inform ui
47 handler.sendEmptyMessage(UPLOAD_FILE_FINISHED);
48 }
49 }).start();
50}
从 APP Server 上获取 BOS 信息代码实现
Plain Text
1public class AppServer {
2 /**
3 * get info from app server for the file to upload to or download from BOS
4 *
5 * @param appServerEndpoint app server
6 * @param userName the app user's name, registered in app server
7 * @param bosOperationType download? upload? or?
8 * @return STS, and BOS endpoint, bucketName, prefix, path, object name etc
9 */
10 public static Map<String, Object> getBosInfoFromAppServer(String appServerEndpoint, String userName, BosOperationType bosOperationType) {
11 String type = "";
12 switch (bosOperationType) {
13 // to simplify
14 case UPLOAD: {
15 type = "upload";
16 break;
17 }
18 case DOWNLOAD: {
19 type = "download";
20 break;
21 }
22 case DOWNLOAD_PROCESSED: {
23 type = "download-processed";
24 break;
25 }
26 default:{
27 break;
28 }
29 }
30 // TODO: this url should be url encoded
31 String appServerUrl = appServerEndpoint + "/?" + "userName=" + userName + "&command=stsToken&type=" + type;
32
33 // create a http client to contact app server to get sts
34 HttpParams httpParameters = new BasicHttpParams();
35 HttpClient httpClient = new DefaultHttpClient(httpParameters);
36
37 HttpGet httpGet = new HttpGet(appServerUrl);
38 httpGet.addHeader("User-Agent", "bos-meitu-app/demo");
39 httpGet.setHeader("Accept", "*/*");
40 try {
41 httpGet.setHeader("Host", new URL(appServerUrl).getHost());
42 } catch (MalformedURLException e) {
43 e.printStackTrace();
44 }
45 httpGet.setHeader("Accept-Encoding", "identity");
46
47 Map<String, Object> bosInfo = new HashMap<String, Object>();
48 try {
49 HttpResponse response = httpClient.execute(httpGet);
50 if (response.getStatusLine().getStatusCode() != 200) {
51 return null;
52 }
53 HttpEntity entity = response.getEntity();
54 long len = entity.getContentLength();
55 InputStream is = entity.getContent();
56 int off = 0;
57 byte[] b = new byte[(int) len];
58 while (true) {
59 int readCount = is.read(b, off, (int) len);
60 if (readCount < 0) {
61 break;
62 }
63 off += readCount;
64 }
65 Log.d("AppServer", new String(b, "utf8"));
66 JSONObject jsonObject = new JSONObject(new String(b, "utf8"));
67 Iterator<String> keys = jsonObject.keys();
68 while (keys.hasNext()) {
69 String key = keys.next();
70 bosInfo.put(key, jsonObject.get(key));
71 }
72 } catch (IOException e) {
73 e.printStackTrace();
74 return null;
75 } catch (JSONException e) {
76 e.printStackTrace();
77 return null;
78 }
79 return bosInfo;
80 }
81
82 public enum BosOperationType {
83 UPLOAD,
84 DOWNLOAD,
85 DOWNLOAD_PROCESSED,
86 }
87}
APP Server端代码样例
APP Server 端基于 Jetty 框架,接口主要处理 Android APP 获取 BOS 信息的请求。APP Server 端会返回临时 AK、SK、Session Token、bucket 名称、资源路径和资源请求的 Endpoint 等参数。以下为 Jetty 处理的代码示例。
Plain Text
1@Override
2public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
3 throws IOException, ServletException {
4
5 // Inform jetty that this request has now been handled
6 baseRequest.setHandled(true);
7
8 if (!request.getMethod().equalsIgnoreCase("GET")) {
9 response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
10 return;
11 }
12
13 // expected url example: localhost:8080/?command=stsToken&type=download
14 Map<String, String[]> paramMap = request.getParameterMap();
15 if (paramMap.get("command") == null || paramMap.get("type") == null) {
16 // invalid request
17 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
18 return;
19 }
20
21 if (!paramMap.get("command")[0].equalsIgnoreCase("stsToken")) {
22 response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
23 return;
24 }
25
26 String responseBody = "";
27 responseBody = getBosInfo(paramMap.get("type")[0]);
28
29 // Declare response encoding and types
30 response.setContentType("application/json; charset=utf-8");
31
32 // Declare response status code
33 response.setStatus(HttpServletResponse.SC_OK);
34
35 // Write back response, utf8 encoded
36 response.getWriter().println(responseBody);
37}
38
39/**
40 * Generates bos info needed by app according to requset type(upload, download etc)
41 * this is the key part for uploading file to bos with sts token
42 * @param bosRequestType
43 * @return utf8 encoded json string
44 */
45public String getBosInfo(String bosRequestType) {
46 // configuration for getting stsToken
47 // bce bos credentials ak sk
48 String bosAk = "your_bos_ak";
49 String bosSk = "your_bos_sk";
50 // bce sts service endpoint
51 String stsEndpoint = "http://sts.bj.baidubce.com";
52
53 BceCredentials credentials = new DefaultBceCredentials(bosAk, bosSk);
54 BceClientConfiguration clientConfig = new BceClientConfiguration();
55 clientConfig.setCredentials(credentials);
56 clientConfig.setEndpoint(stsEndpoint);
57 StsClient stsClient = new StsClient(clientConfig);
58 GetSessionTokenRequest stsReq = new GetSessionTokenRequest();
59 // request expiration time
60 stsReq.setDurationSeconds(1800);
61 GetSessionTokenResponse stsToken = stsClient.getSessionToken(stsReq);
62 String stsTokenAk = stsToken.getCredentials().getAccessKeyId();
63 String stsTokenSk = stsToken.getCredentials().getSecretAccessKey();
64 String stsTokenSessionToken = stsToken.getCredentials().getSessionToken();
65
66 // **to simplify this demo there is no difference between "download" and "upload"**
67 // parts of bos info
68 String bosEndpoint = "http://bj.bcebos.com";
69 String bucketName = "bos-android-sdk-app";
70 if (bosRequestType.equalsIgnoreCase("download-processed")) {
71 // the binded image processing domain set by App developer on bce console
72 bosEndpoint = "http://" + bucketName + ".bj.bcebos.com";
73 }
74
75 // prefix is the bucket name, and does not specify the object name
76 BosInfo bosInfo = new BosInfo(stsTokenAk, stsTokenSk, stsTokenSessionToken, bosEndpoint,
77 bucketName, "", bucketName);
78
79 String res = "";
80 ObjectMapper mapper = new ObjectMapper();
81 try {
82 res = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bosInfo);
83 } catch (JsonProcessingException e) {
84 e.printStackTrace();
85 res = "";
86 }
87 try {
88 res = new String(res.getBytes(), "utf8");
89 } catch (UnsupportedEncodingException e) {
90 // TODO Auto-generated catch block
91 e.printStackTrace();
92 res = "";
93 }
94 return res;
95}