Baidu cloud disk [file API] interface learning "1 』

Source: Internet
Author: User
Over the past few days, I have learned how to use the Baidu cloud Disk File API. I initially wanted to create an online android application. The documents in the application were stored on Baidu cloud disk. The main steps are as follows: 1. Register a Baidu account 2. log on to the Baidu Developer Center 3. Create a mobile application and obtain the corresponding (APIKeySecretKey) 4. Activate pcsAP

Over the past few days, I have learned how to use the Baidu cloud Disk File API. I initially wanted to create an online android application. The documents in the application were stored on Baidu cloud disk. The main steps are as follows: 1. Register a Baidu account 2. log on to the Baidu Developer Center 3. Create a mobile application and obtain the corresponding (API Key Secret Key) 4. Activate the pcs AP

These days are very interesting.LearningBaidu cloud DiskFileAPIInterfaceFirst, I want to create an online android application. The documents in the application are stored on Baidu cloud disk.

The steps are as follows:

1. Register a Baidu account

2. log on to the Baidu Developer Center

3. Create a mobile app and obtain the corresponding (API Key Secret Key)

4. Activate pcs API Permissions

5. Get ACCESS_token (authentication code)

6. Develop applications


Note:

Activate the mobile app and get the key

How to obtain the token from Android



Using the example of writing the corresponding api, I found that there are two situations: one is the get method to submit data, and the other is the post method to submit data.

1. submit data in get mode. We use the following example to obtain the cloud disk information:

Before obtaining cloud disk information, we need to know what data should we prepare:

Request Parameters:

Url: Specifies the url to be accessed. Fixed question: "https://pcs.baidu.com/rest/2.0/pcs/quota"

Method: indicates that the requested cloud disk information value is fixed to "info"

Acceess_token: the access id value we applied.

Response parameters:

Quota: total cloud disk capacity

Used: disk capacity

Request_id: indicates the request, which is useless.

The returned json string is in the following format: {"quota": 123794882560, "used": 83573494688, "request_id": 2853739529}


When I was doing this, you used the Gson tool to convert the json string to the corresponding entity class. The Code is as follows:


[Html]/**
* @ Param URLConnection conn get StringBuffer through get
* @ Return
*/
Private StringBuffer getJsonString (URLConnection conn ){
InputStreamReader isr = null;
BufferedReader br = null;
StringBuffer sb = null;
Try {
Isr = new InputStreamReader (conn. getInputStream (), "gb2312 ");
Br = new BufferedReader (isr );
String line = null;
Sb = new StringBuffer ();
While (line = br. readLine ())! = Null ){
Sb. append (line );
Sb. append ("\ r \ n ");
}
} Catch (UnsupportedEncodingException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
Try {
If (isr! = Null)
Isr. close ();
} Catch (IOException e ){
System. out. println ("an exception occurred when closing the stream ");
E. printStackTrace ();
}
}

Return sb;
}

/**
* @ Return
* @ Throws Exception
* Obtain cloud space information
*/
Public CloudInfo getCloudInfo () throws Exception {
URL u = new URL (https://pcs.baidu.com/rest/2.0/pcs/quota "? Method = info & access_token = value of the token you applied ";
URLConnection conn = u. openConnection (); // open the webpage link
// Obtain the user's cloud disk Information
String cloudJson = this. getJsonString (conn). toString ();

// Parses the object into a class containing this object
Gson gson = new Gson ();
CloudInfo cloudInfo = gson. fromJson (cloudJson, CloudInfo. class );
System. out. println ("cloud disk information:" + cloudInfo );
Return cloudInfo;
}

/**
* @ Param URLConnection conn get StringBuffer through get
* @ Return
*/
Private StringBuffer getJsonString (URLConnection conn ){
InputStreamReader isr = null;
BufferedReader br = null;
StringBuffer sb = null;
Try {
Isr = new InputStreamReader (conn. getInputStream (), "gb2312 ");
Br = new BufferedReader (isr );
String line = null;
Sb = new StringBuffer ();
While (line = br. readLine ())! = Null ){
Sb. append (line );
Sb. append ("\ r \ n ");
}
} Catch (UnsupportedEncodingException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
Try {
If (isr! = Null)
Isr. close ();
} Catch (IOException e ){
System. out. println ("an exception occurred when closing the stream ");
E. printStackTrace ();
}
}

Return sb;
}

/**
* @ Return
* @ Throws Exception
* Obtain cloud space information
*/
Public CloudInfo getCloudInfo () throws Exception {
URL u = new URL (https://pcs.baidu.com/rest/2.0/pcs/quota "? Method = info & access_token = value of the token you applied ";
URLConnection conn = u. openConnection (); // open the webpage link
// Obtain the user's cloud disk Information
String cloudJson = this. getJsonString (conn). toString ();

// Parses the object into a class containing this object
Gson gson = new Gson ();
CloudInfo cloudInfo = gson. fromJson (cloudJson, CloudInfo. class );
System. out. println ("cloud disk information:" + cloudInfo );
Return cloudInfo;
}
[Html] package com. entity;

Import java. lang. reflect. Type;

/**
* @ Author ydcun:
* {"Quota": 123794882560, space quota, in bytes
* "Used": 83573494688. the space used is in bytes.
* "Request_id": 2853739529}
*/
Public class CloudInfo {
Private Double quota;
Private Double used;
Private Double request_id;
/**
* @ Return the quota space quota, in bytes
*/
Public Double getQuota (){
Return quota;
}
/**
* @ Param quota the quota to set space quota, in bytes
*/
Public void setQuota (Double quota ){
This. quota = quota;
}
/**
* @ Return the used space in bytes
*/
Public Double getused (){
Return used;
}
/**
* @ Param used the used to set the used space in bytes
*/
Public void setused (Double used ){
This. used = used;
}
/**
* @ Return the request_id
*/
Public Double getRequest_id (){
Return request_id;
}
/**
* @ Param request_id the request_id to set
*/
Public void setRequest_id (Double request_id ){
This. request_id = request_id;
}
@ Override
Public String toString (){

Return new StringBuffer (). append ("space capacity :"). append (this. getQuota ()/1024/1024 ). append ("M; used :"). append (this. getused ()/1024/1024 ). append ("M ;"). toString ();
}
}

Package com. entity;

Import java. lang. reflect. Type;

/**
* @ Author ydcun:
* {"Quota": 123794882560, space quota, in bytes
* "Used": 83573494688. the space used is in bytes.
* "Request_id": 2853739529}
*/
Public class CloudInfo {
Private Double quota;
Private Double used;
Private Double request_id;
/**
* @ Return the quota space quota, in bytes
*/
Public Double getQuota (){
Return quota;
}
/**
* @ Param quota the quota to set space quota, in bytes
*/
Public void setQuota (Double quota ){
This. quota = quota;
}
/**
* @ Return the used space in bytes
*/
Public Double getused (){
Return used;
}
/**
* @ Param used the used to set the used space in bytes
*/
Public void setused (Double used ){
This. used = used;
}
/**
* @ Return the request_id
*/
Public Double getRequest_id (){
Return request_id;
}
/**
* @ Param request_id the request_id to set
*/
Public void setRequest_id (Double request_id ){
This. request_id = request_id;
}
@ Override
Public String toString (){

Return new StringBuffer (). append ("space capacity :"). append (this. getQuota ()/1024/1024 ). append ("M; used :"). append (this. getused ()/1024/1024 ). append ("M ;"). toString ();
}
}

2. Submit in post ModeFileFor example:

Let's also learn about uploadingFileParameter settings:


Request Parameters:

Url: Specifies the url to be accessed. Fixed question: "https://pcs.baidu.com/rest/2.0/pcs/file"

Method: indicates that the requested cloud disk information value is fixed as "upload"

Acceess_token: the access id value we applied.

Path: the path where we want to upload the data to the cloud disk. For example,/apps/myBaiduCloud is the name of our application. (when you get koten, it will automatically generate the name named after your application name.FileFolder)

File: This is what we want to upload.File(Post upload is required)

Ondup: an optional parameter that identifies a uniqueFileFor specific processing methods, see api

Response parameters:

The returned value is also a json string,

Path: For the uploadedFileSaved full path

Size:FileHow many bytes are there?

Ctime/mtime:FileCreation and modification time

For other parameter descriptions, click the title to view it in the api.

{
"Path": "/apps/album/README. md"
"Size": 372121,
"Ctime": 1234567890,
"Mtime": 1234567890,
"Md5": "cb123afcc12316543ef ",
"Fs_id": 12345,
"Request_id": 4043312669
}

I encapsulated it into the object class when I was doing it. I will not elaborate on it here. Let's focus on the submission.FileHow to submit the code is as follows:


[Java]/**
* @ Param path: cloud disk storage path
* @ Param name the object to be uploadedFile
* @ Return
* @ Throws Exception
*/
Public FileBase uploadFile (String path, File file) throws Exception {
// SimulationFile
String fileName = "README. md ";
File = new File (fileName );
Path = "% 2 fapps % 2 fmybaidu % 2f"; // The url-encoded source code is:-> "/apps/mybaidu/
/"


// Assemble the parameters and URLs that require url value passing
String u = "https://pcs.baidu.com/rest/2.0/pcs/file? Path = "+ path + file. getName () +" & method = upload & access_token = your own token value ";



PostMethod filePost = new PostMethod (u );
// Parameters submitted by post
Part [] parts = {new FilePart (fileName, file )};
// Set multimedia parameters. The function is similar to enctype = "multipart/form-data" in form"
FilePost. setRequestEntity (new MultipartRequestEntity (parts, filePost. getParams ()));
HttpClient clients = new HttpClient ();
// Response code
Int status = clients.exe cuteMethod (filePost );
System. out. println ("uploaded successfully" + path + fileName );

BufferedReader buReader = new BufferedReader (new InputStreamReader (filePost. getResponseBodyAsStream (), "UTF-8 "));
StringBuffer sb = new StringBuffer ();
String line;
While (line = buReader. readLine ())! = Null ){
Sb. append (line );
}
BuReader. close ();

// Parse the object
Gson gson = new Gson ();
FileBase cloudInfo = gson. fromJson (sb. toString (), FileBase. class );

Return cloudInfo;
}

/**
* @ Param path: cloud disk storage path
* @ Param name the object to be uploadedFile
* @ Return
* @ Throws Exception
*/
Public FileBase uploadFile (String path, File file) throws Exception {
// SimulationFile
String fileName = "README. md ";
File = new File (fileName );
Path = "% 2 fapps % 2 fmybaidu % 2f"; // The url-encoded source code is:-> "/apps/mybaidu/
/"


// Assemble the parameters and URLs that require url value passing
String u = "https://pcs.baidu.com/rest/2.0/pcs/file? Path = "+ path + file. getName () +" & method = upload & access_token = your own token value ";



PostMethod filePost = new PostMethod (u );
// Parameters submitted by post
Part [] parts = {new FilePart (fileName, file )};
// Set multimedia parameters. The function is similar to enctype = "multipart/form-data" in form"
FilePost. setRequestEntity (new MultipartRequestEntity (parts, filePost. getParams ()));
HttpClient clients = new HttpClient ();
// Response code
Int status = clients.exe cuteMethod (filePost );
System. out. println ("uploaded successfully" + path + fileName );

BufferedReader buReader = new BufferedReader (new InputStreamReader (filePost. getResponseBodyAsStream (), "UTF-8 "));
StringBuffer sb = new StringBuffer ();
String line;
While (line = buReader. readLine ())! = Null ){
Sb. append (line );
}
BuReader. close ();

// Parse the object
Gson gson = new Gson ();
FileBase cloudInfo = gson. fromJson (sb. toString (), FileBase. class );

Return cloudInfo;
}
After the above Code is successful, we will find README. md in the/apps/mybaidu/directory.File

The code above will also be poured into the corresponding jar package: Download

Commons-codec-1.3.jar
Commons-httpclient-3.0.jar
Commons-logging.jar
Gson-2.2.1.jar
Jsoup-1.6.3.jar


How to use Baidu to use other APIs provides a good demonstration platform:

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.