Java combined with Baidu cloud storage BCS code sharing _java

Source: Internet
Author: User
Tags base64 getmessage hosting aliyun

First, Introduction

Cloud is not a new concept, what is the cloud in the end, you ask me to say a clear I also can not say, the internet is called the cloud. The domestic cloud service provider still has a lot of, there are two main categories, one kind is similar to the Aliyun class host type cloud provider, for example million net and so on the traditional space trader turns over, also has one kind is the application application hosting platform, for instance bae,sae. Relative to the Aliyun and other space business, the application of the hosting platform is lower, for the vast number of bitter-forcing program apes provide a good test platform.

My recently responsible software upgrade program, multi-platform multi-file version, if it is their own framework file server bandwidth can not meet business needs, so the use of Baidu Cloud storage BCS services, now used normally, but occasional intermittent ventilation let me have to turn to Aliyun storage, after all, commercial things still want to commercialize the professional, At least the problem, not like Baidu Cloud storage, customer service are not found. But use it as a technology, or talk about the use of cloud storage.

Second, the use of steps

1, registered Baidu account

I don't need to tell you this.

2, known as the developer

Enter the "Baidu Open Cloud Platform" (do not know their own Baidu), login if not developers, will prompt you to register as a developer, fill out the information on OK.

3. Create Application

Enter Baidu Open Cloud homepage, create a BAE application engine, and create a solution without choosing: Use Bae, unless you still have a website to hang up on. It's OK to have a try. Then select cloud storage after entering and create a bucket (described later).

4, download the SDK

5. Test code

Iii. Difficulties and attention

1, there is no API or API not detailed SDK need to spend a lot of energy to read, or even more convenient to see other people's blog.

2, the concept of understanding

Bucket: After you create an application, you create a Bucket, what is Bucket, you think of it as a disk character under Windows, just as you create a D disk, you can put files, you can put folders, you can create other Bucket. Said Bucket is a letter in fact is not accurate, because it is more like the root directory under Linux, when reading your file, you can not say that my file is: 1.txt. Instead:/1.txt. has been declared in the code.

Object: An object represents a file, he has a lot of meta information and File block composition (reference file system), meta information including file name, file size, time and so on. Before using object, be sure to remember "/";

3. Download authentication

Downloading a private file with an HTTP request requires a authentication parameter. If you read the official API, he only describes the encryption process authorized, but there is no Java version, authorization steps I do not specifically, I also gave the Java implementation, because in the SDK has been implemented, but there is a small problem. SDK generated download address between bucket and filename "/" is encoded, will cause some downloads failed, such as mobile phone QQ can not download. Need to be dealt with again.

4, API key and secret key

Access the application through this.

Iv. Detailed implementation

1, Guide Bag

2, part of the code

Authorized:

Copy Code code as follows:

public class Bcshelper {
Private String host = "";//Host Name: bcs.duapp.com
Private String AccessKey = "";//You can see in the application you created
Private String Secretkey = "";
Private String bucket = "";//bucket name you created
Private Baidubcs Baidubcs = null;

Public Bcshelper () {
This.host = Configuration.gethost ();
This.accesskey = Configuration.getaccesskey ();
This.secretkey = Configuration.getsecretkey ();
This.bucket = Configuration.getbucket ();
Bcscredentials credentials = new Bcscredentials (AccessKey, Secretkey);
Baidubcs = new Baidubcs (credentials, host);
Baidubcs.setdefaultencoding ("UTF-8"); Default UTF-8
}

Uploading and deleting files:

Copy Code code as follows:

/**
* Upload files to BCS
*
* @return Boolean true indicates successful upload
* @param file
* files that need to be uploaded
*
* ******/
public boolean putobject (file file) {
Boolean result = true;
try {
Must have a "/" Start
Putobjectrequest request = new Putobjectrequest (bucket, "/" + file.getname (), file);
Set META information for object
Objectmetadata metadata = new Objectmetadata ();
Request.setmetadata (metadata);
Baidubcs.putobject (Request);
Loggerservice.addloggerbyoperate ("BCS: Uploading Files to BCS:" +file.getname ());
catch (Exception e) {
result = false;
Loggerservice.addloggerbyerror (E.getmessage ());
E.printstacktrace ();
}
return result;
}

/**
* Remove the file from BCS by object name
*
* @param Object
* The name of the object
* @return Boolean true Delete successful
* *****/
public boolean DeleteObject (String object) {
Boolean result = true;
try {
if (Existobject (object)) {
Baidubcs.deleteobject (Bucket, "/" + object);
Loggerservice.addloggerbyoperate ("BCS: Delete files on BCS:" +object);
}
catch (Exception e) {
result = false;
E.printstacktrace ();
Loggerservice.addloggerbyerror (E.getmessage ());
}
return result;
}

To determine whether an object exists:

Copy Code code as follows:

/**
* Determine if the file exists in BCS
*
* @param Object
* Object Name
* @return Boolean true indicates existence
* ***/
public boolean Existobject (String object) {
Boolean result = false;
try {
result = Baidubcs.doesobjectexist (bucket, "/" + object);
catch (Exception e) {
E.printstacktrace ();
}
return result;
}


Write your own build download address:

Copy Code code as follows:

/**
* Get the download address of object
*
* @param Object
* Object Name
* @return String returns the downloaded URL
*******/
public string GetUrl (String object) {
Content that needs to be encrypted
String data = "MBO" + "\ n" + "Method=get" + "\ n" + "bucket=" + Bucket + "\ n" + "object=/" + Object + "\ n";
Results of encryption
String HMACSHA1 = getHmacSHA1 (secretkey, data);
Constructing sign Parameters
String sign = "MBO:" + AccessKey + ":" + hmacsha1;
Url
StringBuilder builder = new StringBuilder ();
Builder.append ("http://");
Builder.append (host);
Builder.append ("/");
Builder.append (bucket);
Builder.append ("/");
Builder.append (object);
Builder.append ("? sign=");
Builder.append (sign);
return builder.tostring ();
}

Signature encryption
private string GetHmacSHA1 (string secretkey, string data) {
String result = "";
try {
Secretkeyspec Signingkey = new Secretkeyspec (Secretkey.getbytes (), "HmacSHA1");
Mac Mac = mac.getinstance ("HmacSHA1");
Mac.init (Signingkey);
byte[] Rawhmac = mac.dofinal (Data.getbytes ());
Base64 base64 = new Base64 ();
@SuppressWarnings ("Static-access")
byte[] enbytes = base64.encodebase64chunked (RAWHMAC);
result = new String (enbytes, "utf-8");
catch (Exception e) {
E.printstacktrace ();
}
return result;
}

Modified SDK Generation Address:

Copy Code code as follows:

* Get the download address of object
*
* @param Object
* Object Name
* @return String returns the downloaded URL
*******/
public string GetUrl (String object) {
String result = "";
Generateurlrequest generateurlrequest = new Generateurlrequest (httpmethodname.get, bucket, "/" + object);
Generateurlrequest.setbcssigncondition (New Bcssigncondition ());
result = Baidubcs.generateurl (generateurlrequest);
Result=result.replacefirst ("%2f", "/");
return result;
}

There are a lot of test code has been provided, I also give out, the need to download their own research, and then encapsulate it can be used in the actual project, I did not find the progress of uploading files, I hope to see to say that, after all, is a rookie.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.