Linked In API (auth token (oauth2)) c#.net



我想知道是否有人可以给我一些关于使用 API 中链接的指示。我以为我已经解决了它,但由于某种原因,当试图获取auth_token时,我只收到 http 400 错误请求。

我的代码,简单地说是:

public string redirectUrl = URLTOREDIRECT;
public String apiKey = APIKEY;
public String apiSecret = APISECRET;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        if (Request.QueryString["code"] != null)
        {
            VerifyAuthentication(Request.QueryString["code"]);
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
        Response.Redirect("https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=apiKey&scope=rw_company_admin&state=DCEEFWF45453sdffef424&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl));
}
public String VerifyAuthentication(string code)
{
   string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
    var sign = "grant_type=authorization_code" + "&code=" + code + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + _consumerkey + "&client_secret=" + _consumerSecret;
   // var postData = String.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&client_id={2}&client_secret={3}", code, HttpUtility.HtmlEncode(redirectUrl), apiKey, apiSecret);
    HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
    webRequest.Method = "POST";
    //This "application/x-www-form-urlencoded"; line is important
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentLength = sign.Length;
    StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
    requestWriter.Write(sign);
    requestWriter.Close();
    StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
    return responseReader.ReadToEnd().ToString() ;
}

出于测试目的,代码都在同一页面中,并且与重定向URL相同。

真的难住了,尝试了所有的变化。

第一位显然有效,因为我被定向到链接以允许应用程序。获取身份验证令牌的第二部分失败。

经过多次挠头,尤里卡时刻 - 不需要在请求中发送信息。

    string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
    var sign = "grant_type=authorization_code&code=" + HttpUtility.UrlEncode(code) + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + apiKey + "&client_secret=" + apiSecret;
    //byte[] byteArray = Encoding.UTF8.GetBytes(sign);

    HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    Stream dataStream = webRequest.GetRequestStream();
    String postData = String.Empty;
    byte[] postArray = Encoding.ASCII.GetBytes(postData);
    dataStream.Write(postArray, 0, postArray.Length);
    dataStream.Close();
    WebResponse response = webRequest.GetResponse();
    dataStream = response.GetResponseStream();

    StreamReader responseReader = new StreamReader(dataStream);
    String returnVal = responseReader.ReadToEnd().ToString();
    responseReader.Close();
    dataStream.Close();
    response.Close();
    return returnVal;

我正在使用这段代码,它工作正常.....C# 代码 ASP.NET:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LI
{
public partial class WebForm3 : System.Web.UI.Page
{
    public string redirectUrl = "http://localhost:64576/WebForm3";
    public string TokenGlobe = ""; 
    public String apiKey = "API_KEY";
    public string retval = "";
    public String apiSecret = "API_Secret";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["code"] != null)
            {
                VerifyAuthentication(Request.QueryString["code"]);
            }
        }
    }
    protected void btnTwit_Click(object sender, EventArgs e)
    {
        var Address = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=" + apiKey + "&redirect_uri=http://localhost:64576/WebForm3&state=987654321&scope=w_share";
        using (var webClient = new WebClient())
        {
            webClient.Headers.Add("x-li-format", "json");
        }
        Response.Redirect(Address);
    }
    public String VerifyAuthentication(string code)
    {
        string authUrl = "https://www.linkedin.com/oauth/v2/accessToken";
        var sign1 = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUrl + "&client_id=" + apiKey + "&client_secret=" + apiSecret + "";
        var sign = "grant_type=authorization_code&code=" + HttpUtility.UrlEncode(code) + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + apiKey + "&client_secret=" + apiSecret;

        HttpWebRequest webRequest = System.Net.WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
        webRequest.Method = "POST";
        webRequest.Host = "www.linkedin.com";
        webRequest.ContentType = "application/x-www-form-urlencoded";
        Stream dataStream = webRequest.GetRequestStream();
        String postData = String.Empty;
        byte[] postArray = Encoding.ASCII.GetBytes(postData);
        dataStream.Write(postArray, 0, postArray.Length);
        dataStream.Close();
        WebResponse response = webRequest.GetResponse();
        dataStream = response.GetResponseStream();

        StreamReader responseReader = new StreamReader(dataStream);
        String returnVal = responseReader.ReadToEnd().ToString();
        responseReader.Close();
        dataStream.Close();
        response.Close();
        var stri = redirectUrl;
        retval = returnVal.ToString();
        var objects = JsonConvert.DeserializeObject<Accountdsdsd>(retval);//JArray.Parse(retval);
        TokenGlobe = objects.access_token;
        var SentStatus = PostLinkedInNetworkUpdate(TokenGlobe, "Hello API"); //Share
        return TokenGlobe;

        // return responseReader.ReadToEnd().ToString();
    }

    private string linkedinSharesEndPoint = "https://api.linkedin.com//v1/people/~/shares?oauth2_access_token={0}&format=json";
    private const string defaultUrl = "http://localhost:64576/WebForm3";
    private const string defaultImageUrl = "http://opusleads.com/opusing/technology/technology%20(1).jpg"; //Image To Post
    public bool PostLinkedInNetworkUpdate(string accessToken, string title, string submittedUrl = defaultUrl, string submittedImageUrl = defaultImageUrl)
    {
        var requestUrl = String.Format(linkedinSharesEndPoint, accessToken);
        var message = new
        {
            comment = "Testing out the LinkedIn Share API with JSON",
            content = new Dictionary<string, string>
    { { "title", title },
        { "submitted-url", submittedUrl },
        {"submitted-image-url" , submittedImageUrl}
    },
            visibility = new
            {
                code = "anyone"
            }
        };
        var requestJson = new JavaScriptSerializer().Serialize(message);
        var client = new WebClient();
        var requestHeaders = new NameValueCollection
{
    {"Content-Type", "application/json" },
            {"x-li-format", "json" }
};
        client.Headers.Add(requestHeaders);
        var responseJson = client.UploadString(requestUrl, "POST", requestJson);
        var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
        return response.ContainsKey("updateKey");
    }
}
//Json Parsing
public class Accountdsdsd
{
    public string access_token { get; set; }
    public string expires_in { get; set; }
}
} 

最新更新