문제
C# 응용 프로그램에서 사용자의 트위터 상태를 업데이트하려고합니다.
나는 웹을 검색하고 몇 가지 가능성을 발견했지만 트위터의 인증 프로세스의 최근 (?) 변화에 약간 혼란스러워합니다. 나는 또한 무엇을 발견했는지 발견했다 관련 stackoverflow 게시물, 그러나 그것은 작동하지 않는 코드 스 니펫을 매우 특징적이기 때문에 단순히 내 질문에 대답하지 않습니다.
검색 API가 아닌 REST API에 도달하려고합니다. 즉, 엄격한 OAUTH 인증에 부응해야합니다.
나는 두 가지 해결책을 보았다. 그만큼 Twitterizer 프레임 워크 잘 작동했지만 외부 DLL이므로 소스 코드를 사용합니다. 예를 들어,이를 사용하는 코드는 매우 명확하고 다음과 같습니다.
Twitter twitter = new Twitter("username", "password");
twitter.Status.Update("Hello World!");
나는 또한 조사했다 예다의 트위터 도서관, 그러나 이것은 위의와 동일한 코드를 시도 할 때 인증 프로세스라고 생각하는 것에 실패했습니다 (YEDDA는 상태 업데이트 자체의 사용자 이름과 비밀번호를 기대하지만 다른 모든 것은 동일합니다).
웹에서 명확한 컷 답변을 찾을 수 없었기 때문에 StackoverFlow로 가져 왔습니다.
외부 DLL 종속성없이 C# 응용 프로그램에서 트위터 상태 업데이트를 작동시키는 가장 간단한 방법은 무엇입니까?
감사
해결책
Twitterizer 프레임 워크를 좋아하지만 소스가없는 것을 좋아하지 않는다면 왜 소스를 다운로드하십시오? (또는 찾아보세요 당신이 무엇을하고 있는지보고 싶다면 ...)
다른 팁
나는 휠을 다시 발명하는 팬이 아닙니다. 특히 인기있는 기능의 100%를 제공하는 이미 존재하는 제품에 관해서는 특히 그렇습니다. 실제로 소스 코드가 있습니다 트위터 필요한 변경을 할 수 있도록 ASP.NET MVC 애플리케이션을 나란히 실행합니다 ...
DLL 참조가 존재하기를 원하지 않는 경우 C#의 업데이트를 코딩하는 방법에 대한 예입니다. 이것을 확인하십시오 DreamIncode.
/*
* A function to post an update to Twitter programmatically
* Author: Danny Battison
* Contact: gabehabe@hotmail.com
*/
/// <summary>
/// Post an update to a Twitter acount
/// </summary>
/// <param name="username">The username of the account</param>
/// <param name="password">The password of the account</param>
/// <param name="tweet">The status to post</param>
public static void PostTweet(string username, string password, string tweet)
{
try {
// encode the username/password
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
// determine what we want to upload as a status
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
// connect with the update page
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
// set the method to POST
request.Method="POST";
request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change!
// set the authorisation levels
request.Headers.Add("Authorization", "Basic " + user);
request.ContentType="application/x-www-form-urlencoded";
// set the length of the content
request.ContentLength = bytes.Length;
// set up the stream
Stream reqStream = request.GetRequestStream();
// write to the stream
reqStream.Write(bytes, 0, bytes.Length);
// close the stream
reqStream.Close();
} catch (Exception ex) {/* DO NOTHING */}
}
트위터에 물건을 게시하는 가장 간단한 방법은 사용하는 것입니다. 기본 인증 , 그다지 강하지 않습니다.
static void PostTweet(string username, string password, string tweet)
{
// Create a webclient with the twitter account credentials, which will be used to set the HTTP header for basic authentication
WebClient client = new WebClient { Credentials = new NetworkCredential { UserName = username, Password = password } };
// Don't wait to receive a 100 Continue HTTP response from the server before sending out the message body
ServicePointManager.Expect100Continue = false;
// Construct the message body
byte[] messageBody = Encoding.ASCII.GetBytes("status=" + tweet);
// Send the HTTP headers and message body (a.k.a. Post the data)
client.UploadData("http://twitter.com/statuses/update.xml", messageBody);
}
노력하다 Linq to Twitter. 찾다 Linq to Twitter Twitter REST API v1.1에서 작동하는 미디어 완전 코드 예제로 상태 업데이트. 솔루션도 다운로드 할 수 있습니다.
LINQ에서 트위터 코드 샘플
var twitterCtx = new TwitterContext(auth);
string status = "Testing TweetWithMedia #Linq2Twitter " +
DateTime.Now.ToString(CultureInfo.InvariantCulture);
const bool PossiblySensitive = false;
const decimal Latitude = StatusExtensions.NoCoordinate;
const decimal Longitude = StatusExtensions.NoCoordinate;
const bool DisplayCoordinates = false;
string ReplaceThisWithYourImageLocation = Server.MapPath("~/test.jpg");
var mediaItems =
new List<media>
{
new Media
{
Data = Utilities.GetFileBytes(ReplaceThisWithYourImageLocation),
FileName = "test.jpg",
ContentType = MediaContentType.Jpeg
}
};
Status tweet = twitterCtx.TweetWithMedia(
status, PossiblySensitive, Latitude, Longitude,
null, DisplayCoordinates, mediaItems, null);
노력하다 트위터 샤프 . 찾다 미디어 완료 코드 예제를 사용한 TweetSharp 업데이트 상태 Twitter REST API v1.1과 함께 작동합니다. 솔루션도 다운로드 할 수 있습니다.
트윗 샤프 코드 샘플
//if you want status update only uncomment the below line of code instead
//var result = tService.SendTweet(new SendTweetOptions { Status = Guid.NewGuid().ToString() });
Bitmap img = new Bitmap(Server.MapPath("~/test.jpg"));
if (img != null)
{
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Seek(0, SeekOrigin.Begin);
Dictionary<string, Stream> images = new Dictionary<string, Stream>{{"mypicture", ms}};
//Twitter compares status contents and rejects dublicated status messages.
//Therefore in order to create a unique message dynamically, a generic guid has been used
var result = tService.SendTweetWithMedia(new SendTweetWithMediaOptions { Status = Guid.NewGuid().ToString(), Images = images });
if (result != null && result.Id > 0)
{
Response.Redirect("https://twitter.com");
}
else
{
Response.Write("fails to update status");
}
}
다음은 우수한 코드를 사용하여 최소한의 다른 솔루션입니다. 비동기 Nuget 패키지 및 Microsoft 's HttpClient
. 이 솔루션은 또한 귀하가 자신을 대신하여 게시하고 있다고 가정하므로 액세스 토큰 키/비밀을 이미 가지고 있지만 흐름이 매우 쉽지 않더라도 (Asyncoauth Docs 참조).
using System.Threading.Tasks;
using AsyncOAuth;
using System.Net.Http;
using System.Security.Cryptography;
public class TwitterClient
{
private readonly HttpClient _httpClient;
public TwitterClient()
{
// See AsyncOAuth docs (differs for WinRT)
OAuthUtility.ComputeHash = (key, buffer) =>
{
using (var hmac = new HMACSHA1(key))
{
return hmac.ComputeHash(buffer);
}
};
// Best to store secrets outside app (Azure Portal/etc.)
_httpClient = OAuthUtility.CreateOAuthClient(
AppSettings.TwitterAppId, AppSettings.TwitterAppSecret,
new AccessToken(AppSettings.TwitterAccessTokenKey, AppSettings.TwitterAccessTokenSecret));
}
public async Task UpdateStatus(string status)
{
try
{
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"status", status}
});
var response = await _httpClient.PostAsync("https://api.twitter.com/1.1/statuses/update.json", content);
if (response.IsSuccessStatusCode)
{
// OK
}
else
{
// Not OK
}
}
catch (Exception ex)
{
// Log ex
}
}
}
이것은 httpclient의 성격으로 인해 모든 플랫폼에서 작동합니다. 완전히 다른 서비스를 위해 Windows Phone 7/8 에서이 방법을 직접 사용합니다.