I am using very simple code to post message in twitter. The code is as given below:
public void UpdateStatus(string username, string password, string tweetMsg)
{
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweetMsg);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
request.Credentials = new NetworkCredential(username, password);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ServicePoint.Expect100Continue = false;
string statusUpdate = string.Empty;
using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
{
statusUpdate = "status=" + System.Web.HttpUtility.UrlEncode(tweetMsg);
sw.Write(statusUpdate);
}
using (HttpWebResponse resp = (HttpWebResponse) request.GetResponse())
{
// Handle response here
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
catch (WebException ex)
{
Console.WriteLine("Web Error: {0}", ex.Message);
if (ex.Response != null)
{
HttpWebResponse r = (HttpWebResponse)ex.Response;
using (StreamReader esr = new StreamReader(r.GetResponseStream()))
{
Console.WriteLine("Error: {0}", esr.ReadToEnd());
}
}
}
catch (IOException ex)
{
Console.WriteLine("I/O Error: {0}", ex.Message);
}
}
I am not sure why this code is not working. I am getting the exception
The remote server returned an error: (401) Unauthorized.
But, whichever site I am referring, everywhere I find that people are able to post their messages using the same code.
Can anybody please tell me what I am missing in this code? The site that I referred for this code is http://www.dreamincode.net/forums/topic/120468-twitter-api-posting-status/
Thanks in advance....
Hari
The Twitter API no longer supports Basic Auth for authentication. You need to switch to OAuth which uses tokens instead of passwords.
Twitter's guide to transitioning from Basic Auth to OAuth
OAuth homepage
Related
To consume a Web API in ASP.NET MVC server side I am using 'HttpClient'. HttpClient sends a request to the Web API and receives a response. Then I convert the response data that came from the Web API to a model and then render it into a view.
The problem is when there is an error in the web api, my client is not receiving the custom error message that was sent.
The web api sends a status code = 400 and a ReasonPhrase with my custom message, but when it gets to the client, it is a status code = 500 and the ReasonPhrase = 'Internal Server error'.
Why?
Web api code - the WebApi2Controller method called by the client which calls a data access layer then sends result back to client:
[HttpPost]
[Route("getbloggersinfo/{argsData}/")]
public IHttpActionResult GetBloggersInfo(ArgsToPassToApi argsToPassToApi)
{
IHttpActionResult httpActionResult;
HttpResponseMessage httpResponseMessage;
try
{
BloggerInfoResults bloggerInfoResults = new BloggerInfoResults();
bloggerInfoResults = dataAccessLayer.GetBloggersInfo(argsToPassToApi.UserName, argsToPassToApi.IpAddress);
httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, bloggerInfoResults);
}
catch (Exception ex)
{
httpResponseMessage = Request.CreateResponse(HttpStatusCode.BadRequest);
httpResponseMessage.ReasonPhrase = ex.Message;
}
httpActionResult = ResponseMessage(httpResponseMessage);
return httpActionResult;
}
The web api code - the data access layer method called by the WebApi2Controller:
public BloggerInfoResults GetBloggersInfo(string userName, string ipAddress)
{
string userFriendlyMessage = "Unable to get the Blogger's info. We have been notified and are working to resolve this. Please do not continue.";
BloggerInfoResults bloggerInfoResults = new BloggerInfoResults();
SqlDataReader bloggerInfoDataReader = null;
try
{
dbFunc.OpenDB();
SqlCommand cmd = new SqlCommand("dbo.GetBloggersInfo", dbFunc.objConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#a_UserName", userName);
cmd.Parameters.AddWithValue("#a_IpAddress", ipAddress);
bloggerInfoDataReader = cmd.ExecuteReader();
while (bloggerInfoDataReader.Read())
{
bloggerInfoResults.UserId = Convert.ToInt32(bloggerInfoDataReader["UserId"]);
bloggerInfoResults.UserName = bloggerInfoDataReader["UserName"].ToString();
bloggerInfoResults.HasProfileSwitch = Convert.ToBoolean(bloggerInfoDataReader["HasProfileSwitch"]);
}
return bloggerInfoResults;
}
catch (SqlException sqlex)
{
if (sqlex.Message.Contains("Critical"))
{
// A "critical" error coming from the stored procedure.
currentDateTime = DateTime.Now;
sendAlertEmailResult = SendAlertEmailToStaff(currentDateTime, userName, ipAddress);
if (sendAlertEmailResult == "")
{
// The alert email was sent successfully.
// Throw - for setting the UI. Send a user friendly message.
throw new Exception(userFriendlyMessage);
}
else
{
// Not sent successfully. I have no choice but to send the verbose message as it was NOT stored in the error log and I will need to see it
// when debugging.
// Throw - for setting the UI.
throw new Exception(criticalErrorPrepend + "Error in DataAccessLayer/GetBloggersInfo(). Sending an alert email for the initial sql exception error: " + sqlex.Message + ". Now getting this error: " + sendAlertEmailResult);
}
}
else
{
// Not coming from the stored procedure. Like if the stored procedure above was not named properly, does not exist, parameter missing, etc.
errorMessage = "Sql Exception Error in DataAccessLayer/GetBloggersInfo(). Using 'GetBloggersInfo' s/p. Error: " + sqlex.Message;
// Log the error and send an alert email.
currentDateTime = DateTime.Now;
processErrorLogAndSendAlertEmailResult = ProcessErrorLogAndSendAlertEmail(currentDateTime, userName, errorMessage, additionalInfoForLog, ipAddress);
if (processErrorLogAndSendAlertEmailResult != "")
{
// Throw - for setting the UI.
throw new Exception(criticalErrorPrepend + "Error in DataAccessLayer/GetBloggersInfo(). Using 'GetBloggersInfo' s/p. Logging the initial sql exception error: " + sqlex.Message + ". Now getting this error: " + processErrorLogAndSendAlertEmailResult);
}
else
{
// Throw - for setting the UI. Send a user friendly message.
throw new Exception(userFriendlyMessage);
}
}
}
catch (Exception ex)
{
errorMessage = "Error in DataAccessLayer/GetBloggersInfo(). Using 'GetBloggersInfo' s/p. Error: " + ex.Message;
// Log the error and send an alert email.
currentDateTime = DateTime.Now;
processErrorLogAndSendAlertEmailResult = ProcessErrorLogAndSendAlertEmail(currentDateTime, userName, errorMessage, additionalInfoForLog, ipAddress);
if (processErrorLogAndSendAlertEmailResult != "")
{
// Throw - for setting the UI.
throw new Exception(criticalErrorPrepend + "Error in DataAccessLayer/GetBloggersInfo(). Using 'GetBloggersInfo' s/p. Logging the initial error: " + ex.Message + ". Now getting this error: " + processErrorLogAndSendAlertEmailResult);
}
else
{
// Throw - for setting the UI. Send a user friendly message.
throw new Exception(userFriendlyMessage);
}
}
finally
{
if (bloggerInfoDataReader != null)
{
// Close the reader.
bloggerInfoDataReader.Close();
}
// Close the database.
dbFunc.CloseDB();
}
}
The custom message being thrown (throw new Exception (....)) from the data access layer method back to the WebApi2Controller method (my custom message):
The error being sent to the client from the WebApi2Controller (a status code = 400 and ReasonPhrase with my custom message):
The client code which calls the web api controller method using httpclient:
public async Task<BloggerInfoResults> GetBloggersInfo(string userName, string webApiUrl, string myIpAddress)
{
try
{
BloggerInfoResults bloggerInfoResults = new BloggerInfoResults();
ArgsToPassToApi argsToPassToApi = new ArgsToPassToApi();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(webApiUrl);
argsToPassToApi.UserName = userName;
argsToPassToApi.IpAddress = myIpAddress;
string restOfUrl = "/api/profileandblog/getbloggersinfo/" + argsToPassToApi + "/";
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string payLoad = JsonConvert.SerializeObject(argsToPassToApi);
HttpContent argsData = new StringContent(payLoad, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(restOfUrl, argsData);
if (response.IsSuccessStatusCode)
{
var entry = response.Content.ReadAsStringAsync().Result;
bloggerInfoResults = JsonConvert.DeserializeObject<BloggerInfoResults>(entry);
}
else
{
// The web api sent an error response.
bloggerInfoResults.ApiErrorMessage = "Web api error. Reason: " + response.ReasonPhrase;
}
// Return the model.
return bloggerInfoResults;
}
}
catch (Exception)
{
throw;
}
}
The error being received (a status code = 400 and the ReasonPhrase = 'Internal Server error'.):
I am new to xamarin and Rest API.
I am Trying to call Rest API from Xamrine IOS code as follow. My moto is to get List(From API) and Display in list view(Device). But it is giving me error "Bad Request". but when put same URL in POSTMAN , gives me proper response. Please help me out here.
Postman Call Image
Call from Postman
URL: http://localhost/MobileAppAPI/
Client Code:
static List<AuditModel> _audits = new List<AuditModel>();
public static string GetAudits()
{
string URL = "http://localhost/MobileAppAPI/api/Values/Get?id=1000";
string data = CreateObject(URL);
return APIHelper.APIHelper.CreateObject(URL);
}
public static string CreateObject(string URL)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/json";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
try
{
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write("");
}
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
return response;
}
}
}
}
catch (Exception e)
{
Console.Out.WriteLine("-----------------");
Console.Out.WriteLine(e.Message);
return e.Message;
}
return "";
}
API Code:
// GET api/values/5
public string Get(int id)
{
return "value";
}
Exception:
Unhandled Exception:
System.Net.WebException: Error: ConnectFailure (Connection refused)
I am using OAuth authenication in Jira to test some methods in jira using JIRA Rest Java Client. I have got the access token using OAuth authenication that I need to pass on Jira URL. Here is all what I have got to get access token.
Token is 38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Token secret is cnDSL8oJyuoaQdRcFDwgHzLppSshQn9b
Retrieved request token. go to http://bmh1060149:8080/plugins/servlet/oauth/authorize?oauth_token=38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Access token is : 015CeJiH8cpI5R3OKpNco158kApq8YwV
Now I am passing that access token to Jira URL but I am getting an empty array. Please let me know where I am doing wrong or what changes do I need to incorporate into my code to make this thing work. Here is my code.
public void getAllIssueTypesUsingOAuth(JiraCQCredential jcqcred) {
System.out.println("Inside getAllIssuetypeAssociatedToProject for JiraAdapterImpl");
//String username = jcqcred.getUserName();
//String password = jcqcred.getPassword();
String jiraURL = jcqcred.getJiraUrl();
if (!jiraURL.endsWith("/")) {
jiraURL = jiraURL + "/";
}
try {
String accessToken = JiraAdapterImpl.getAccessToken(); // This method is giving me access token
URL url = new URL(jiraURL + "rest/api/2" + "/" + "issuetype?access_token=" + accessToken);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String issueTypes = sb.toString();
System.out.println("Issuetype associated to project are\n" + issueTypes);
JSONArray jsonArray = new JSONArray(issueTypes);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String issueNames = (String) jsonObject.get("name");
System.out.println(issueNames);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
Its giving me an empty array like []
Hi After searching the little bit I finally managed to a find the solution to the above problem. After getting the access token just pass that access token to the makeAuthenticatedRequest(url, accessToken) method that will give you the resultant data which you want to retrive. Here url is the url which you want to hit to get the resultant data.
private AtlassianOAuthClient getJiraOAuthClient() {
final String baseURI = "http://bmh1060149:8080";
final String consumerKey = "hardcoded-consumer";
final String consumerPrivatekey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFkPMZQaTqsSXI+bSI65rSVaDzic6WFA3WCZMVMi7lYXJAUdkXo4DgdfvEBO21Bno3bXIoxqS411G8S53I39yhSp7z2vcB76uQQifi0LEaklZfbTnFUXcKCyfwgKPp0tQVA+JZei6hnscbSw8qEItdc69ReZ6SK+3LHhvFUUP1nLhJDsgdPHRXSllgZzqvWAXQupGYZVANpBJuK+KAfiaVXCgA71N9xx/5XTSFi5K+e1T4HVnKAzDasAUt7Mmad+1PE+56Gpa73FLk1Ww+xaAEvss6LehjyWHM5iNswoNYzrNS2k6ZYkDnZxUlbrPDELETbz/n3YgBHGUlyrXi2PBjAgMBAAECggEAAtMctqq6meRofuQbEa4Uq5cv0uuQeZLV086VPMNX6k2nXYYODYl36T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qCyTMq56omiLdu941oWfsOnwffWRBInvrUWTj6yGHOYUtg2z4xESUoFYDeWwe/vX6TugL3oXSX3Sy3KWGlJhn/OmsN2fgajHRip0=";
AtlassianOAuthClient jiraoAuthClient = new AtlassianOAuthClient(consumerKey, consumerPrivatekey, baseURI, "");
return jiraoAuthClient;
}
Here is the code to get Access Token
private String getAccessToken() {
AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
TokenSecretVerifierHolder requestToken = jiraoAuthClient.getRequestToken();
String authorizeUrl = jiraoAuthClient.getAuthorizeUrlForToken(requestToken.token);
String token = requestToken.token;
String tokenSecret = requestToken.secret;
System.out.println("Token is " + requestToken.token);
System.out.println("Token secret is " + requestToken.secret);
System.out.println("Retrieved request token. go to " + authorizeUrl);
String accessToken = jiraoAuthClient.swapRequestTokenForAccessToken(token, tokenSecret, "");
System.out.println("Access token is : " + accessToken);
return accessToken;
}
This is the method you call to retrieve the data.
public void getAllCommentOfIssueUsingOAuth() {
logger.info("Inside getAllCommentOfIssue for JiraAdapterImpl");
AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
String accessToken = getAccessToken();
String url = "your Jira URL";
String responseAsString = jiraoAuthClient.makeAuthenticatedRequest(url, accessToken);
System.out.println(responseAsString);
}
This will give you the resultant JSON data or XML data in resultantString.
I want to oauth authentication like
Login using Google OAuth 2.0 with C#
But i don't want to authentication prompt popup
i want to get token directly without popup..
public ActionResult CodeLele()
{
if (Session.Contents.Count > 0)
{
if (Session["loginWith"] != null)
{
if (Session["loginWith"].ToString() == "google")
{
try
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string code = words[1];
if (code != null)
{
//get the access token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
if (serStatus != null)
{
string accessToken = string.Empty;
accessToken = serStatus.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
// This is where you want to add the code if login is successful.
// getgoogleplususerdataSer(accessToken);
}
else
{ }
}
else
{ }
}
else
{ }
}
}
catch (WebException ex)
{
try
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
//var messageFromServer = obj.error.message;
//return messageFromServer;
return obj.error_description;
}
catch (Exception exc)
{
throw exc;
}
}
}
}
}
return Content("done");
}
public ActionResult JeClick()
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id;
Session["loginWith"] = "google";
return Redirect(Googleurl);
}
The credentials window (popup) is how you ask the user if you can access their data. There is no way to get access to a users data without asking the user first if you may access their data. That is how Oauth2 works.
If you are accessing your own data then you can use something called a Service account. Service accounts are pre authorized. You can take the service account and grant it access to your google calendar, you could give it access to a folder in Google drive. Then you can authenticate using the service account. Service accounts are like dummy users.
My article about service accounts: Google Developer service account
I am making an application written in C# : get information youtube videos !
I have a question as the title ! Who can help me ?
You can use HttpWebRequest to pull information from the site as a String.
using System.Net;
using System.IO;
using System.Windows.Forms;
string result = null;
string url = "http://www.youtube.com"; //Your youtube channel here
WebResponse response = null;
StreamReader reader = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
response = request.GetResponse();
reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
}
catch (Exception ex)
{
// handle error
MessageBox.Show(ex.Message);
}
finally
{
if (reader != null)
reader.Close();
if (response != null)
response.Close();
}
Now you can parse the string to take advantage of the data that you want by using meta tags.