上云无忧 > 文档中心 > 百度智能云对象存储BOS手机美图APP实践代码示例
对象存储BOS
百度智能云对象存储BOS手机美图APP实践代码示例

文档简介:
示例代码以 Java 语言为例讲解美图 APP 的实现,代码分为 APP 客户端和应用服务器端两部分。 APP 端代码主要包括 BOSClient 初始化、从 APP Server 端获取 BOS 信息、及上传文件到 BOS 三个功能模块。
*此产品及展示信息均由百度智能云官方提供。免费试用 咨询热线:400-826-7010,为您提供专业的售前咨询,让您快速了解云产品,助您轻松上云! 微信咨询
  免费试用、价格特惠

代码示例

示例代码以 Java 语言为例讲解美图 APP 的实现,代码分为 APP 客户端和应用服务器端两部分。

APP 客户端代码样例

APP 端代码主要包括 BOSClient 初始化、从 APP Server 端获取 BOS 信息、及上传文件到 BOS 三个功能模块。

BOSClient 初始化

public class bos {
	private string ak = null;
    private string sk = null;
    private string endpoint = null;
    private string ststoken = null;
    private bosclient client = null;

    public bos(string ak, string sk, string endpoint, string ststoken) {
        this.ak = ak;
        this.sk = sk;
        this.endpoint = endpoint;
        this.ststoken = ststoken;
        client = createclient();
    }
	
    public bosclient createclient() {
        bosclientconfiguration config = new bosclientconfiguration();
        bcecredentials credentials = null;
        if (ststoken != null && !ststoken.equalsignorecase("")) {
            credentials = new defaultbcesessioncredentials(ak, sk, ststoken);
        } else {
            credentials = new defaultbcecredentials(ak, sk);
        }
        config.setendpoint(endpoint);
        config.setcredentials(credentials);
        return new bosclient(config);
    }
	
    public void uploadfile(string bucket, string object, file file) {
        client.putobject(bucket, object, file);
    }
	
    public void uploadfile(string bucket, string object, inputstream inputstream) {
        client.putobject(bucket, object, inputstream);
    }
	
    public void uploadfile(string bucket, string object, byte[] data) {
        client.putobject(bucket, object, data);
    }
	
    public byte[] downloadfilecontent(string bucket, string object) {
        return client.getobjectcontent(bucket, object);
    }
}

上传文件到 BOS 代码实现

public void uploadPicToBos() {
    // 1. get pic params from ui: file name, file location uri etc
    // 2. send params to app server and get sts, bucket name and region
    // 3. upload selected pic to bos with sts etc, which bos client needs

    EditText et = (EditText) findViewById(R.id.app_server_addr_edittext);
    final String appServerAddr = et.getText().toString();

	    new Thread(new Runnable() {
        @Override
        public void run() {
            Map<String, Object> bosInfo = AppServer.getBosInfoFromAppServer(appServerAddr, "user-demo",
                    AppServer.BosOperationType.UPLOAD);

            if (bosInfo == null) {
                return;
            }
            showToast(bosInfo.toString(), Toast.LENGTH_LONG);

            String ak = (String) bosInfo.get("ak");
            String sk = (String) bosInfo.get("sk");
            String stsToken = (String) bosInfo.get("stsToken");
            String endpoint = (String) bosInfo.get("endpoint");
            String bucketName = (String) bosInfo.get("bucketName");
            String objectName = (String) bosInfo.get("objectName");
            String prefix = (String) bosInfo.get("prefix");
            Log.i("UploadFileToBos", bosInfo.toString());

            // specify a object name if the app server does not specify one
            if (objectName == null || objectName.equalsIgnoreCase("")) {
                objectName = ((EditText) findViewById(R.id.bos_object_name_edittext)).getText().toString();
                if (prefix != null && !prefix.equalsIgnoreCase("")) {
                    objectName = prefix + "/" + objectName;
                }
            }

            Bos bos = new Bos(ak, sk, endpoint, stsToken);
            try {
                byte[] data = Utils.readAllFromStream(MainActivity.this.getContentResolver().openInputStream
(selectedPicUri));
                bos.uploadFile(bucketName, objectName, data);
            } catch (Throwable e) {
                Log.e("MainActivity/Upload", "Failed to upload file to bos: " + e.getMessage());
                showToast("Failed to upload file: " + e.getMessage());
                return;
            }
            // finished uploading file, send a message to inform ui
            handler.sendEmptyMessage(UPLOAD_FILE_FINISHED);
        }
    }).start();
}

从 APP Server 上获取 BOS 信息代码实现

public class AppServer {
    /**
     * get info from app server for the file to upload to or download from BOS
     *
     * @param appServerEndpoint app server
     * @param userName          the app user's name, registered in app server
     * @param bosOperationType  download? upload? or?
     * @return STS, and BOS endpoint, bucketName, prefix, path, object name etc
     */
    public static Map<String, Object> getBosInfoFromAppServer(String appServerEndpoint, String userName,
 BosOperationType bosOperationType) {
        String type = "";
        switch (bosOperationType) {
            // to simplify
            case UPLOAD: {
                type = "upload";
                break;
            }
            case DOWNLOAD: {
                type = "download";
                break;
            }
            case DOWNLOAD_PROCESSED: {
                type = "download-processed";
                break;
            }
            default:{
                break;
            }
        }
        // TODO: this url should be url encoded
        String appServerUrl = appServerEndpoint + "/?" + "userName=" + userName
 + "&command=stsToken&type=" + type;

        // create a http client to contact app server to get sts
        HttpParams httpParameters = new BasicHttpParams();
        HttpClient httpClient = new DefaultHttpClient(httpParameters);
	
        HttpGet httpGet = new HttpGet(appServerUrl);
        httpGet.addHeader("User-Agent", "bos-meitu-app/demo");
        httpGet.setHeader("Accept", "*/*");
        try {
            httpGet.setHeader("Host", new URL(appServerUrl).getHost());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        httpGet.setHeader("Accept-Encoding", "identity");
	
        Map<String, Object> bosInfo = new HashMap<String, Object>();
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() != 200) {
                return null;
            }
            HttpEntity entity = response.getEntity();
            long len = entity.getContentLength();
            InputStream is = entity.getContent();
            int off = 0;
            byte[] b = new byte[(int) len];
            while (true) {
                int readCount = is.read(b, off, (int) len);
                if (readCount < 0) {
                    break;
                }
                off += readCount;
            }
            Log.d("AppServer", new String(b, "utf8"));
            JSONObject jsonObject = new JSONObject(new String(b, "utf8"));
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                bosInfo.put(key, jsonObject.get(key));
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
        return bosInfo;
    }
	
    public enum BosOperationType {
        UPLOAD,
        DOWNLOAD,
        DOWNLOAD_PROCESSED,
    }
}

APP Server端代码样例

APP Server 端基于 Jetty 框架,接口主要处理 Android APP 获取 BOS 信息的请求。APP Server 端会返回临时 AK、SK、Session Token、bucket 名称、资源路径和资源请求的 Endpoint 等参数。以下为 Jetty 处理的代码示例。

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Inform jetty that this request has now been handled
    baseRequest.setHandled(true);

    if (!request.getMethod().equalsIgnoreCase("GET")) {
        response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        return;
    }

    // expected url example: localhost:8080/?command=stsToken&type=download
    Map<String, String[]> paramMap = request.getParameterMap();
    if (paramMap.get("command") == null || paramMap.get("type") == null) {
        // invalid request
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (!paramMap.get("command")[0].equalsIgnoreCase("stsToken")) {
        response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        return;
    }

    String responseBody = "";
    responseBody = getBosInfo(paramMap.get("type")[0]);

    // Declare response encoding and types
    response.setContentType("application/json; charset=utf-8");

    // Declare response status code
    response.setStatus(HttpServletResponse.SC_OK);

    // Write back response, utf8 encoded
    response.getWriter().println(responseBody);
}

/**
 * Generates bos info needed by app according to requset type(upload, download etc)
 * this is the key part for uploading file to bos with sts token
 * @param bosRequestType 
 * @return utf8 encoded json string
 */
public String getBosInfo(String bosRequestType) {
    // configuration for getting stsToken
    // bce bos credentials ak sk
    String bosAk = "your_bos_ak";
    String bosSk = "your_bos_sk";
    // bce sts service endpoint
    String stsEndpoint = "http://sts.bj.baidubce.com";

    BceCredentials credentials = new DefaultBceCredentials(bosAk, bosSk);
    BceClientConfiguration clientConfig = new BceClientConfiguration();
    clientConfig.setCredentials(credentials);
    clientConfig.setEndpoint(stsEndpoint);
    StsClient stsClient = new StsClient(clientConfig);
    GetSessionTokenRequest stsReq = new GetSessionTokenRequest();
    // request expiration time
    stsReq.setDurationSeconds(1800);
    GetSessionTokenResponse stsToken = stsClient.getSessionToken(stsReq);
    String stsTokenAk = stsToken.getCredentials().getAccessKeyId();
    String stsTokenSk = stsToken.getCredentials().getSecretAccessKey();
    String stsTokenSessionToken = stsToken.getCredentials().getSessionToken();

    // **to simplify this demo there is no difference between "download" and "upload"**
    // parts of bos info
    String bosEndpoint = "http://bj.bcebos.com";
    String bucketName = "bos-android-sdk-app";
    if (bosRequestType.equalsIgnoreCase("download-processed")) {
        // the binded image processing domain set by App developer on bce console
        bosEndpoint = "http://" + bucketName + ".bj.bcebos.com";
    }

    // prefix is the bucket name, and does not specify the object name
    BosInfo bosInfo = new BosInfo(stsTokenAk, stsTokenSk, stsTokenSessionToken, bosEndpoint,
            bucketName, "", bucketName);

    String res = "";
    ObjectMapper mapper = new ObjectMapper();
    try {
        res = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bosInfo);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        res = "";
    }
    try {
        res = new String(res.getBytes(), "utf8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        res = "";
    }
    return res;
}

相似文档
  • HTTP(HyperText Transfer Protocol),即超文本传输协议,是互联网上应用最为广泛的一种网络协议。设计HTTP最初的目的是为了提供一种发布和接收HTML页面的方法。通过HTTP或者HTTPS协议请求的资源由统一资源标识符(Uniform Resource Identifiers,URI)来标识。
  • 混合云融合了公有云和私有云,是近年来云计算的主要模式和发展方向。企业出于安全考虑更愿意将数据存放在私有云中,但是同时又希望获得公有云的计算资源。百度智能云混合云方案中客户 IDC 和百度智能云 VPC 通过专线/ VPN 打通,实现云上云下业务紧密连接,既可以利用云上资源的按需使用和易扩展的特性,又可以利用本地 IDC 满足合规性要求。
  • 存储分发场景下,BOS用于存放网站的静态图片、视频文件和应用服务的下载内容等文件。存储分发场景通常有以下特点: 静态文件访问量大,访问频率高,服务器负载高;
  • 本文主要介绍如何利用 CDN 的动态加速特性来提升客户端数据上传 BOS 过程的传输速度和稳定性。 BOS 联合 CDN 推出数据上传动态加速功能,主要是为了满足用户在使用 BOS 上传数据场景中的加速需求。
  • A网站将自己的静态资源如图片或视频等存放在百度智能云存储的BOS上。B网站在未经A允许的情况下,使用A网站的图片或视频资源,放置到自己的网站中。由于BOS是按照使用量收费,这样网站B盗取了网站A的空间和流量,而A没有获取任何利益却承担了资源使用费。B盗用A资源放到自己网站的行为即为盗链。
官方微信
联系客服
400-826-7010
7x24小时客服热线
分享
  • QQ好友
  • QQ空间
  • 微信
  • 微博
返回顶部