您的位置:首页 > Web前端 > HTML

html调用hadoop WebHDFS REST API

2015-01-05 17:32 471 查看
首先,hadoop的WebHDFS支持通过REST API用http的方式访问HDFS。
原文链接:http://hadoop.apache.org/common/docs/current/hadoop-yarn/hadoop-yarn-site/WebHDFS.html

通过REST API能完成很多,如上传下载,查看文件,创建目录等操作. 本地的hadoop版本是hadoop2.0,装上了httpfs,端口是14000. 这里以上传文件(原文是Create and Write to a File)为例。

上传文件分为两步,

第一步先提交一个不自动重定向的,不发送文件数据的put请求 如,我要上传文件test.txt到user目录。执行以下命令:

curl -i -X PUT "http://10.20.18.1:14000/webhdfs/v1/user/test.txt?user.name=hdfs&op=CREATE"

[&overwrite=<true|false>][&blocksize=<LONG>][&replication=<SHORT>] [&permission=<OCTAL>][&buffersize=<INT>]"

//后面是可选参数其中overwrite是是否覆盖,默认为false,但是官方文档上说true是个Valid Values(晕)

//可以看出块大小,副本数,文件权限都是可以设置的。 执行之后会得到一些返回,如下:

HTTP/1.1 307 Temporary Redirect Server: Apache-Coyote/1.1 Set-Cookie: hadoop.auth="u=hdfs&p=hdfs&t=simple&e=1345220043113&s=ikU/wiUsFtaTHrkPQmaya5PHjkQ=";
Version=1; Path=/ Location: http://10.20.18.1:14000/webhdfs/v1/user/test.txt?op=CREATE&user.name=hdfs&data=true Content-Type: application/json Content-Length: 0 Date: Fri, 17 Aug 2012 06:14:03 GMT

//注意到返回值是307

记下headers中的Set-Cookie和Location的内容。

例如,我把Set-Cookie的内容写到cookie.txt中,把Location写到url.txt中。

第二步:上传文件test.txt:

curl -i -X PUT -T test.txt -b cookie.txt --header "Content-Type: application/octet-stream" "`cat url.txt`"
这时就可以在hdfs上看到你上传的文件了。
当然,在命令行中完成hadoop-httpfsde restAPI调用肯定不是httpfs的本意。

这里用XMLHttpResquest来上传文件。作为例子。完整代码请查看附件。

在/usr/lib/hadoop-httpfs/webapps/ROOT下创建abc.html,这样可以通过httpfs的端口访问了

this.xhr.open( p.method, p.url, true);
this.xhr.setRequestHeader("Content-Type","application/octet-stream");//设置Content-Type属性
this.xhr.onreadystatechange = function() {
if( this.xhr.readyState != 4 ) { return; }
}.bind( this );
this.xhr.send( null );//发送文件,这里使用空,null

这里的this.xhr是个XMLHttpResquest对象。在this.xhr.send( null );之前,XMLHttpResquest

已经完成了cookie和location的重定向(注意上面出现了的307,xmlhttpresqust在send的时候会对307返回值的请求重定向)。
本文出自 “稀饭吃了不顶饿” 博客,请务必保留此出处/article/4304473.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: