简体   繁体   English

LinkedIn API-发布到网上论坛或个人资料共享会返回401身份验证代码

[英]LinkedIn API - posting to a group or profile share returns a 401 authentication code

I had a problem with no documented solution that I could find. 我有一个找不到文件化解决方案的问题。 Now that I found it, I'm posting it here in the event someone runs into the same issue. 现在,我找到了它,如果有人遇到相同问题,我将其发布在这里。

I followed the steps to authenticate with LinkedIn and get an access token, I was able to retrieve my profile information and groups that I belong to without any issue. 我按照步骤进行了LinkedIn身份验证并获得了访问令牌,从而能够毫无问题地检索我的个人资料信息和所属的组。

Next, I wanted to make a post to a group using the API. 接下来,我想使用API​​在论坛中发帖。

The LinkedIn API docs show the use of file_get_contents , but it was not working for me. LinkedIn API文档显示了file_get_contents的用法,但不适用于我。 The access token was correct, but I was receiving a 401 response . 访问令牌正确,但是我收到401 response Refer to https://developer.linkedin.com/documents/code-samples . 请参阅https://developer.linkedin.com/documents/code-samples Because I added ignore_errors=1 , the group post was made, but still returning a 401 . 因为我添加了ignore_errors=1 ,所以可以进行群组发布,但仍返回401

As reference, this was the piece of code that I had to change to resolve the 401 : 作为参考,这是我必须更改以解决401那段代码:

$context = stream_context_create(
  array('http' => 
    array('method' =>"POST",                        
      'header'=> "Content-Type:application/json\r\n",
      'content' => $body,
      'ignore_errors' => '1'
    )
  )
);
$res = file_get_contents($url, false, $context);

Solution Overview 解决方案概述

Using the LinkedIn API to post to a group, the steps are: 使用LinkedIn API发布到网上论坛,步骤是:

Set up the URL: 设置URL:

$params = array('oauth2_access_token' => YOUR_ACCESS_TOKEN);

$url = 'https://api.linkedin.com/v1/groups/{group_id}/posts?' . http_build_query($params);

Set the body for the POST 设置POST的正文

$bodyArray = array(
  'title' => $title,
  'summary' => $userMessage,
  'content' => array(
    'title' => '$title2',
    'submitted-image-url' => $pictureUrl,                
    'submitted-url' => $redirectUrl,
    'description' => $userMessage                
  )            
);
$body = json_encode($bodyArray);

Use CURL instead of get_file_contents This is what I needed to change to get it working. 使用CURL代替get_file_contents这是我需要进行更改以使其正常运行的方法。

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $url,
    CURLOPT_POST => 1,
    CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json"),
    CURLOPT_POSTFIELDS => $body,
));     

// here we execute the code and check for response code
curl_exec($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($http_status == "201"){
  echo date('g:i') . ' Posted to LinkedIn group <br>';
}else{
  echo date('g:i') . '<b>LinkedIn error: ' . $http_status . '</b><br>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM