简体   繁体   中英

Getting error : The remote server returned an error: (401) Unauthorized. , while posting my website comments to twitter. Using C#

Am trying to post my website comments on my twitter wall, but i am getting an error

The remote server returned an error: (401) Unauthorized

My tried code is as :-

using System;
using System.Web;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Text;
using System.Configuration;

namespace Dotned.UI.Framework
{
public class TwitterClient
{
    public string Username { get; set; }
    public string Password { get; set; }
    public Exception Error { get; set; }
    private string _twitterUpdateUrl = "http://twitter.com/statuses/update.json";

    public TwitterClient(string userName, string password)
    {
        this.Username = userName;
        this.Password = password;
    }

    public void SendMessage(string message)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_twitterUpdateUrl);
            request.Credentials = new NetworkCredential(this.Username, this.Password);

            SetRequestParams(request);

            string post = string.Format("status={0}", HttpUtility.UrlEncode(message));

            using (Stream requestStream = request.GetRequestStream())
            {
                using (StreamWriter writer = new StreamWriter(requestStream))
                {
                    writer.Write(post);
                }
            }

            WebResponse response = request.GetResponse();
            string content;

            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    content = reader.ReadToEnd();
                }
            }
        }
        catch (Exception ex)
        {
            Error = ex;
        }
    }

    private static void SetRequestParams(HttpWebRequest request)
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        request.Timeout = 50000;
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
    }

}
}

The process is getting break at WebResponse response = request.GetResponse(); .

Any suggestions are highly appreciable.

You must authenticate with OAuth. You can either visit Twitter's OAuth Page to see how to write this yourself or visit their 3rd Party Library Page to find a library to help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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