Post/Reply a post by Social feed REST API in SharePoint 2013

As we know, we can post/reply a post in Newsfeed for my site, but how can we apply by JS? SharePoint provide the REST API for developer to apply it.

You can use the SharePoint 2013 Representational State Transfer (REST) service to do the same things that you can do with the .NET client object models and the JavaScript object model. The REST service exposes resources that
correspond to SharePoint objects, properties, and methods. To use the REST service, you build and send HTTPGET andPOST requests to the resource endpoints that represent the tasks you want to do

The endpoint URIs for most feed tasks begin with the SocialRestFeedManager resource (social.feed), followed by themy resource or thepost resource:

  • The my resource represents the current user. When used inline in the endpoint URI, it sets the context of the request to the current user. For example,http://contoso.com/_api/social.feed/my/news gets the
    newsfeed for the current user.

here is the result:

a. Create the UI via html

b. New and Reply a post via my js code

c. Verify the result in Newsfeed

a. you can new a post (Post)

b. you can reply a specify post via getting the post id when click any post title(Reply)

c. you can view all post by current user (All)

here is the rest api in detail:

New a post:

$.ajax( {
        url: weburl + "/_api/social.feed/my/Feed/Post",
        type: "POST",
        data: JSON.stringify( {
            'restCreationData':{
                '__metadata':{
                    'type':'SP.Social.SocialRestPostCreationData'
                },
                'ID': null,
                'creationData':{
                    '__metadata':{
                        'type':'SP.Social.SocialPostCreationData'
                    },
                    'ContentText': “the post content text”,
                    'UpdateStatusText':false
                }
            }
        }),
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(){console.log("success to post ");},
        error: function (xhr, ajaxOptions, thrownError) {
            alert("POST error:\n" + xhr.status + "\n" + thrownError);
        }
    });

Reply a post:

    $.ajax( {
        url: weburl + "/_api/social.feed/post/reply",
        type: "POST",
        data: JSON.stringify( {
            'restCreationData':{
                '__metadata':{
                    'type':'SP.Social.SocialRestPostCreationData'
                },
                'ID': PostID
                'creationData':{
                    '__metadata':{
                        'type':'SP.Social.SocialPostCreationData'
                    },
                    'ContentText': ”the reply content text”,
                    'UpdateStatusText':false
                }
            }
        }),
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(){console.log("reply to success");},
        error: function (xhr, ajaxOptions, thrownError) {
            alert("POST error:\n" + xhr.status + "\n" + thrownError);
        }
    });

The complete code:

Note: just add the code inside the Script Editor web part in page

Post : <input type="text" class="postcontent"/>
<div class="newpost" style="width:40px; background-color:gray; padding-left:10px"> Post </div>

Reply : <input type="text" class="replycontent"/>
<div class="replypost" style="width:40px; background-color:gray; padding-left:10px;margin-top:10px"> Reply </div>

    <div class="allpost" style="width:40px; background-color:gray; padding-left:10px;margin-top:10px"> All </div>
<div class="message"></div>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
var feedManagerEndpoint;

// Get the SPAppWebUrl parameter from the query string and build
// the feed manager endpoint.
$(document).ready(function () {
    var appweburl= "http://tristan-02";

    feedManagerEndpoint = decodeURIComponent(appweburl)+ "/_api/social.feed";

    $(".newpost").on("click", function(){
        postToMyFeed();
    });
    $(".replypost").on("click", function(){
        Reply();
    });

    $(".allpost").on("click", function(){
        getMyFeed();

    });
});

//reply post

function Reply() {
    $.ajax( {
        url: feedManagerEndpoint + "/post/reply",
        type: "POST",
        data: JSON.stringify( {
            'restCreationData':{
                '__metadata':{
                    'type':'SP.Social.SocialRestPostCreationData'
                },
                'ID': $(".postcontent").val(),
                'creationData':{
                    '__metadata':{
                        'type':'SP.Social.SocialPostCreationData'
                    },
                    'ContentText':$(".replycontent").val(),
                    'UpdateStatusText':false
                }
            }
        }),
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(){console.log("reply to success");},
        error: function (xhr, ajaxOptions, thrownError) {
            alert("POST error:\n" + xhr.status + "\n" + thrownError);
        }
    });
}

// Publish a post to the current user's feed by using the
// "<app web URL>/_api/social.feed/my/Feed/Post" endpoint.
function postToMyFeed() {
    $.ajax( {
        url: feedManagerEndpoint + "/my/Feed/Post",
        type: "POST",
        data: JSON.stringify( {
            'restCreationData':{
                '__metadata':{
                    'type':'SP.Social.SocialRestPostCreationData'
                },
                'ID': null,
                'creationData':{
                    '__metadata':{
                        'type':'SP.Social.SocialPostCreationData'
                    },
                    'ContentText':$(".postcontent").val(),
                    'UpdateStatusText':false
                }
            }
        }),
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(){console.log("success to post ");},
        error: function (xhr, ajaxOptions, thrownError) {
            alert("POST error:\n" + xhr.status + "\n" + thrownError);
        }
    });
}

// Get the current user's feed by using the
// "<app web URL>/_api/social.feed/my/Feed" endpoint.
function getMyFeed() {
    $.ajax( {
        url: feedManagerEndpoint + "/my/Feed",
        headers: {
            "accept": "application/json;odata=verbose"
        },
        success: feedRetrieved,
        error: function (xhr, ajaxOptions, thrownError) {
            alert("GET error:\n" + xhr.status + "\n" + thrownError);
        }
    });
}

// Parse the JSON data and iterate through the feed.
function feedRetrieved(data) {
    var stringData = JSON.stringify(data);
    var jsonObject = JSON.parse(stringData); 

    var feed = jsonObject.d.SocialFeed.Threads;
    var threads = feed.results;
    var feedContent = "";
    for (var i = 0; i < threads.length; i++) {
        var thread = threads[i];
        var participants = thread.Actors;
        var owner = participants.results[thread.OwnerIndex].Name;
        feedContent += "<div class='postitem'>" + "<span class='owner'>" + owner + " : </span>"+ "<span class = 'posttext'>" +thread.RootPost.Text + "</span>"+ "<div class='postid'>"+ thread.RootPost.Id+"</div>" +"</div>" ;
    }
    $(".message").html(feedContent); 

    $(".postitem").on("click", function(){
        var id = $(this).find(".postid").text();
        $(".postcontent").val(id);

    });
}

</script>

<style>
.postitem {
    margin-top:10px;
}
.postitem > .owner{
    color: green;
}
.postitem > .postid{
    display:none;
}

.postitme > .posytext{
   //
}

</style>



时间: 2024-10-05 17:07:53

Post/Reply a post by Social feed REST API in SharePoint 2013的相关文章

Custom Social Newsfeed in SharePoint 2013

Requirement Implement a custom social newsfeed, user can retrieve/new/reply/like/unlike a post, and ability to auto retrieve hastags when input "#". you would be notice that the UI is same as the default Newsfeed in SharePoint 2013. Correct! I r

【转】Spring websocket 使用

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html https://spring.io/guides/gs/messaging-stomp-websocket/ https://github.com/rstoyanchev/spring-websocket-portfolio 项目中用到了消息的实时推送,查资料后用到了Spring websocket,找了很多资料,还是感

SharePoint 2013 WebTemplates

SharePoint 2013 WebTemplates You are here: Home / SharePoint 2013 WebTemplates January 24, 2013 Tags: SharePoint 2013 Web Templates by Raghavendra Shanbhag Please find below the list of available templates in SharePoint 2013 RTM, this would help you

LR脚本示例

Get请求: web_reg_save_param("ResponseBody", "LB=", "RB=", "Search=Body", LAST); lr_start_transaction("Ts_GetAttentionList"); web_reg_find("Search=Body",//这里说明在Body的范围内查找 "SaveCount=ret_Count&q

SharePoint 2013 版本功能对比

原文:SharePoint 2013 版本功能对比 前言:在SharePoint使用中,经常纠结于版本问题,SharePoint 2013主要有免费的Foundation和收费的标准版.企业版三个版本,他们之间的功能上是不一样的,找了一些资料才发现下面的这个表格,还是很清楚的描述了各个版本的区别,拿过来给大家看看.大家如果想看原版的,我附加链接在最后,点进去看即可,还可以下载PDF文件.   Foundation Standard Enterprise Developer       Acces

SharePoint 2013 开发——其他社交功能

博客地址:http://blog.csdn.net/FoxDave 上一篇讲了如何获取用户配置文件的相关属性,它属于SharePoint 2013社交功能的一个小的构成部分.社交功能是SharePoint 2013改进的一大亮点.可以在现有网站上开启社交功能或者新建一个专门用于社交用途的社区网站,社交功能包括关注(人或内容).艾特@.#等功能.有清晰的用户积分制度等等.由于工作中不会有太多关于这方面的开发需求,并且个人觉得这部分做得挺不错,基本的需求应该是够用了(强大的或许就不在SharePoi

Threads Events QObjects

Events and the event loop Being an event-driven toolkit, events and event delivery play a central role in Qt architecture. In this article we'll not give a comprehensive coverage about this topic; we'll instead focus on some thread-related key concep

拿nodejs快速搭建简单Oauth认证和restful API server攻略

拿nodejs快速搭建简单Oauth认证和restful API server攻略:http://blog.csdn.net/zhaoweitco/article/details/21708955 最近一直在鼓捣这个东西,拿出来分享下一下经验吧,其实很简单,一点也不难. 首先需求是这样,给自己的网站要增加API服务,API分为两种,公共的和私有授权的,授权的使用Oauth方法认证身份,API格式均为JOSN和JSONP. 嗯,别的语言我也没怎么学过,首先是找合适的框架进行实现吧.本身网站使用的e

SharePoint 2013 搜索报错&quot;Unable to retrieve topology component health. This may be because the admin component is not up and running&quot;

环境描述 Windows 2012 R2,SharePoint 2013(没有sp1补丁),sql server 2012 错误描述 搜索服务正常,但是爬网一直在Crawling Full,但是爬不到任何东西,而且不会停止,爬了一宿什么都没有爬到: 爬网不止,爬了一宿什么都没有爬到,错误如下: 去15/logs里面找日志: Non-OAuth request. IsAuthenticated=True, UserIdentityName=0#.w|domain\user, ClaimsCount