---
title: "Baidu云盘【文件API】接口学习 『一』 "
author: "eddysoft"
date: "2013-10-21T17:26:30Z"
tags: []
categories: ["行业应用"]
slug: "baidu-api"
draft: false
lastmod: "2013-10-21T17:26:30Z"
id: 1961794
url: "https://eddysoft.iteye.com/blog/1961794"
---

这几天很有兴致的学习了百度云盘文件API接口的使用；初步是想做一个在线android应用，应用中的文档是存放在百度云盘的。

主要是分一下几个[步骤：](http://developer.baidu.com/wiki/index.php?title=docs%2Fpcs%2Fguide%2Foverview)

1.注册百度账号

2.登录百度开发者中心

3.创建移动应用，获取对应的（API Key   Secret Key）

4.开通pcs API权限

5.[获取ACCESS\_token(认证编码)](http://developer.baidu.com/wiki/index.php?title=docs%2Fpcs%2Fguide%2Ftoken_authorize)

6.开发应用

 

注意：

开通移动应用，获取key

获取token的时候我使用的安卓获取的方式

![](http://img.blog.csdn.net/20130528102036759)

通过我写对应api的例子我发现，其实就两种情况：一种是get方式提交数据，另外一种是post方式提交数据

**1.get方式提交数据，[我们用获取云盘的信息为例：](http://developer.baidu.com/wiki/index.php?title=docs%2Fpcs%2Frest%2Ffile_data_apis_list#.E7.A9.BA.E9.97.B4.E9.85.8D.E9.A2.9D.E4.BF.A1.E6.81.AF)**

获取云盘信息前我们要知道，我们要准备好什么数据：

请求参数：

url: 标明我们要访问的网址路径   值固定问“https://pcs.baidu.com/rest/2.0/pcs/quota”

method：标明我们是请求云盘信息   值固定为“info”

acceess\_token:准入标识  值是我们自己申请的

接收返回参数：

        quota：云盘总容量

used:云盘使用容量

request\_id：该请求的表示，没啥用

        返回的一个json串如下格式：{"quota":123794882560, "used":83573494688,"request\_id":2853739529}

 

我在做的时候你使用Gson工具将json串转换到对应的entity类中了 代码如下：

 

**\[html]** [view plain](http://blog.csdn.net/manageer/article/details/8982988 "view plain")[copy](http://blog.csdn.net/manageer/article/details/8982988 "copy")[print](http://blog.csdn.net/manageer/article/details/8982988 "print")[?](http://blog.csdn.net/manageer/article/details/8982988 "?")

01. /\**
02. * @param URLConnection conn通过get方式获取StringBuffer
03. * @return
04. \*/
05. private StringBuffer getJsonString(URLConnection conn) {
06. InputStreamReader isr = null;
07. BufferedReader br = null;
08. StringBuffer sb = null;
09. try {
10. isr = new InputStreamReader(conn.getInputStream(),"gb2312");
11. br = new BufferedReader(isr);
12. String line = null;
13. sb = new StringBuffer();
14. while ((line = br.readLine()) != null) {
15. sb.append(line);
16. sb.append("\\r\\n");
17. }
18. } catch (UnsupportedEncodingException e) {
19. e.printStackTrace();
20. } catch (IOException e) {
21. e.printStackTrace();
22. }finally{
23. try {
24. if(isr!=null)
25. isr.close();
26. } catch (IOException e) {
27. System.out.println("流关闭是异常");
28. e.printStackTrace();
29. }
30. }
31. return sb;
32. }
33. /\**
34. * @return
35. * @throws Exception
36. *             获取云空间的信息
37. \*/
38. public CloudInfo getCloudInfo() throws Exception {
39. URL u = new URL(https://pcs.baidu.com/rest/2.0/pcs/quota"?method=info&access\_token=你申请的token的值";
40. URLConnection conn = u.openConnection();// 打开网页链接
41. // 获取用户云盘信息
42. String cloudJson = this.getJsonString(conn).toString();
43. // 解析成对象 下面有这个实体对象的类
44. Gson gson = new Gson();
45. CloudInfo cloudInfo = gson.fromJson(cloudJson, CloudInfo.class);
46. System.out.println("云盘信息："+cloudInfo);
47. return cloudInfo;
48. }

```
	/**
	 * @param URLConnection conn通过get方式获取StringBuffer
	 * @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("流关闭是异常");
				e.printStackTrace();
			}
		}

		return sb;
	}

	/**
	 * @return
	 * @throws Exception
	 *             获取云空间的信息
	 */
	public CloudInfo getCloudInfo() throws Exception {
		URL u = new URL(https://pcs.baidu.com/rest/2.0/pcs/quota"?method=info&access_token=你申请的token的值";
		URLConnection conn = u.openConnection();// 打开网页链接
		// 获取用户云盘信息
		String cloudJson = this.getJsonString(conn).toString();

		// 解析成对象 下面有这个实体对象的类
		Gson gson = new Gson();
		CloudInfo cloudInfo = gson.fromJson(cloudJson, CloudInfo.class);
		System.out.println("云盘信息："+cloudInfo);
		return cloudInfo;
	}
```

**\[html]** [view plain](http://blog.csdn.net/manageer/article/details/8982988 "view plain")[copy](http://blog.csdn.net/manageer/article/details/8982988 "copy")[print](http://blog.csdn.net/manageer/article/details/8982988 "print")[?](http://blog.csdn.net/manageer/article/details/8982988 "?")

01. package com.entity;
02. import java.lang.reflect.Type;
03. /\**
04. * @author ydcun 获取云空间的信息 例如：
05. *              {"quota":123794882560, 空间配额，单位为字节
06. *               "used":83573494688, 已使用空间大小 单位为字节。
07. *               "request\_id":2853739529}
08. \*/
09. public class CloudInfo{
10. private Double quota;
11. private Double used;
12. private Double request\_id;
13. /\**
14. * @return the quota  空间配额，单位为字节
15. \*/
16. public Double getQuota() {
17. return quota;
18. }
19. /\**
20. * @param quota the quota to set  空间配额，单位为字节
21. \*/
22. public void setQuota(Double quota) {
23. this.quota = quota;
24. }
25. /\**
26. * @return the used 已使用空间大小 单位为字节
27. \*/
28. public Double getused() {
29. return used;
30. }
31. /\**
32. * @param used the used to set 已使用空间大小 单位为字节
33. \*/
34. public void setused(Double used) {
35. this.used = used;
36. }
37. /\**
38. * @return the request\_id
39. \*/
40. public Double getRequest\_id() {
41. return request\_id;
42. }
43. /\**
44. * @param request\_id the request\_id to set
45. \*/
46. public void setRequest\_id(Double request\_id) {
47. this.request\_id = request\_id;
48. }
49. @Override
50. public String toString() {
51. return new StringBuffer().append("空间容量:").append(this.getQuota()/1024/1024).append("M;  已用:").append(this.getused()/1024/1024).append("M; ").toString();
52. }
53. }

```
package com.entity;

import java.lang.reflect.Type;

/**
 * @author ydcun 获取云空间的信息 例如：
 * 				{"quota":123794882560, 空间配额，单位为字节
 *        		 "used":83573494688, 已使用空间大小 单位为字节。
 *          	 "request_id":2853739529}
 */
public class CloudInfo{
	private Double quota;
	private Double used;
	private Double request_id;
	/**
	 * @return the quota  空间配额，单位为字节
	 */
	public Double getQuota() {
		return quota;
	}
	/**
	 * @param quota the quota to set  空间配额，单位为字节
	 */
	public void setQuota(Double quota) {
		this.quota = quota;
	}
	/**
	 * @return the used 已使用空间大小 单位为字节
	 */
	public Double getused() {
		return used;
	}
	/**
	 * @param used the used to set 已使用空间大小 单位为字节
	 */
	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("空间容量:").append(this.getQuota()/1024/1024).append("M;  已用:").append(this.getused()/1024/1024).append("M; ").toString();
	}
}
```

 

**2.通过post方式提交  [我用上传单个文件为例子](http://developer.baidu.com/wiki/index.php?title=docs%2Fpcs%2Frest%2Ffile_data_apis_list#.E4.B8.8A.E4.BC.A0.E5.8D.95.E4.B8.AA.E6.96.87.E4.BB.B6)：**

同样我们也先了解下上传文件要参数设置：

 

请求参数：

url: 标明我们要访问的网址路径   值固定问“https://pcs.baidu.com/rest/2.0/pcs/file”

method：标明我们是请求云盘信息   值固定为“upload”

acceess\_token:准入标识  值是我们自己申请的

path:是我们要上传到云盘的那个路径下     如/apps/myBaiduCloud/        myBaiduCloud是我们的应用名称（当你获取koten后就会自动生成以你应用名称为名的文件夹）

file：这个就是我们要上传的文件了（要求用post方式上传）

ondup：可选参数，标识当有重名的文件的时候处理方式具体见api

接收返回参数：

       返回的也是json串，

path：为我们上传的文件保存的全路径

size：文件的大小有多少字节

ctime/mtime：文件的创建修改时间

其他参数介绍点小标题去api中查看

{  
　    "path" : "/apps/album/README.md"  
　    "size" : 372121,  
　    "ctime" : 1234567890,  
　    "mtime" : 1234567890,  
　    "md5" : "cb123afcc12453543ef",  
　    "fs\_id" : 12345,  
   　"request\_id":4043312669  
}

我在做的时候也是将其封装到实体类中了，这里和上面一样不详述，我们重点看下提交文件是怎么提交的代码如下：

 

 

**\[java]** [view plain](http://blog.csdn.net/manageer/article/details/8982988 "view plain")[copy](http://blog.csdn.net/manageer/article/details/8982988 "copy")[print](http://blog.csdn.net/manageer/article/details/8982988 "print")[?](http://blog.csdn.net/manageer/article/details/8982988 "?")

01. /\**
02. * @param path 云盘存放路径
03. * @param name 要上传的文件
04. * @return
05. * @throws Exception
06. \*/
07. public FileBase uploadFile(String path,File file) throws Exception{
08. //模拟文件
09. String fileName="README.md";
10. file = new File(fileName);
11. path="%2fapps%2fmybaidu%2f";    //  我用的是url编码过源码为：-&gt;  "/apps/mybaidu/
12. /"
13. //将需要url传值的参数和url组装起来
14. String u ="https://pcs.baidu.com/rest/2.0/pcs/file?path="+path+file.getName()+"&method=upload&access\_token=你自己申请的token值";
15. PostMethod filePost = new PostMethod(u);
16. //post提交的参数
17. Part\[] parts = {new FilePart(fileName,file)};
18. //设置多媒体参数，作用类似form表单中的enctype="multipart/form-data"
19. filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
20. HttpClient clients = new HttpClient();
21. //响应代码
22. int status = clients.executeMethod(filePost);
23. System.out.println("成功上传"+path+fileName);
24. BufferedReader buReader = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream(),"utf-8"));
25. StringBuffer sb = new StringBuffer();
26. String line;
27. while((line=buReader.readLine())!=null){
28. sb.append(line);
29. }
30. buReader.close();
31. // 解析成对象
32. Gson gson = new Gson();
33. FileBase cloudInfo = gson.fromJson(sb.toString(), FileBase.class);
34. return cloudInfo;
35. }

```
/**
	 * @param path 云盘存放路径
	 * @param name 要上传的文件
	 * @return
	 * @throws Exception 
	 */
	public FileBase uploadFile(String path,File file) throws Exception{
		//模拟文件
		String fileName="README.md";
		file = new File(fileName);
		path="%2fapps%2fmybaidu%2f";    //  我用的是url编码过源码为：->  "/apps/mybaidu/
/"
		
		
		//将需要url传值的参数和url组装起来
		String u ="https://pcs.baidu.com/rest/2.0/pcs/file?path="+path+file.getName()+"&method=upload&access_token=你自己申请的token值";

		
		
		PostMethod filePost = new PostMethod(u);
		//post提交的参数
		Part[] parts = {new FilePart(fileName,file)};
		//设置多媒体参数，作用类似form表单中的enctype="multipart/form-data" 
		filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
		HttpClient clients = new HttpClient();
		//响应代码
		int status = clients.executeMethod(filePost);
		System.out.println("成功上传"+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();
		
		// 解析成对象
		Gson gson = new Gson();
		FileBase cloudInfo = gson.fromJson(sb.toString(), FileBase.class);
		
		return cloudInfo;
	}
```

上面代码成功后我们就会在/apps/mybaidu/目录下找到README.md文件

 

上面代码执行还要倒入对应的jar包：[下载](http://download.csdn.net/detail/ydcun/5464481)

commons-codec-1.3.jar  
commons-httpclient-3.0.jar  
commons-logging.jar  
gson-2.2.1.jar  
jsoup-1.6.3.jar

 

其他的api怎么用百度给了一个很好的[演示平台](http://developer.baidu.com/wiki/index.php?title=docs%2Fpcs%2Frest%2Ffile_data_apis_list#.E4.B8.8A.E4.BC.A0.E5.8D.95.E4.B8.AA.E6.96.87.E4.BB.B6)：

![](http://img.blog.csdn.net/20130528110659763)

 

好了剩下的就大家自己去模式吧！

 

 

用什么问题联系我我们一起探讨----[ydcun](http://blog.csdn.net/ydcun)