链接在API(auth token(oauth2))c#.net

时间:2013-12-19 15:20:45

标签: c# asp.net api linkedin

我想知道是否有人可以给我一些关于在API中使用链接的指示。我以为我有这个问题但是出于某种原因,当我试图获得auth_token时,我只得到了http 400 Bad Request。

我的代码就是:

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() ;
}

代码全部在同一页面中用于测试目的,与redirectUrl的页面相同。

真的很难过,尝试了各种变化。

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

2 个答案:

答案 0 :(得分:5)

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

    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;

答案 1 :(得分:0)

我正在使用此代码并且它工作正常..... 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; }
}
}