コード例 #1
0
  public void getObjectSample() {

    // 构造下载文件请求
    GetObjectRequest get = new GetObjectRequest(testBucket, testObject);

    try {
      // 同步执行下载请求,返回结果
      GetObjectResult getResult = oss.getObject(get);

      Log.d("Content-Length", "" + getResult.getContentLength());

      // 获取文件输入流
      InputStream inputStream = getResult.getObjectContent();

      byte[] buffer = new byte[2048];
      int len;

      while ((len = inputStream.read(buffer)) != -1) {
        // 处理下载的数据,比如图片展示或者写入文件等
        Log.d("asyncGetObjectSample", "read length: " + len);
      }
      Log.d("asyncGetObjectSample", "download success.");

      // 下载后可以查看文件元信息
      ObjectMetadata metadata = getResult.getMetadata();
      Log.d("ContentType", metadata.getContentType());

    } catch (ClientException e) {
      // 本地异常如网络异常等
      e.printStackTrace();
    } catch (ServiceException e) {
      // 服务异常
      Log.e("RequestId", e.getRequestId());
      Log.e("ErrorCode", e.getErrorCode());
      Log.e("HostId", e.getHostId());
      Log.e("RawMessage", e.getRawMessage());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #2
0
    @Override
    public GetObjectResult parse(Response response) throws IOException {
      GetObjectResult result = new GetObjectResult();

      result.setRequestId(response.header(OSSHeaders.OSS_HEADER_REQUEST_ID));
      result.setStatusCode(response.code());
      result.setResponseHeader(parseResponseHeader(response));
      result.setMetadata(parseObjectMetadata(result.getResponseHeader()));
      result.setContentLength(response.body().contentLength());
      result.setObjectContent(response.body().byteStream());

      // keep body stream open for reading content
      return result;
    }