I got the following problem:
I am trying to implement Instagram into my website. However I am stuck on the step where I need to get the Acces token. The api's documentation says I need to request it like this :
curl \-F 'client_id=CLIENT-ID' \
-F 'client_secret=CLIENT-SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=YOUR-REDIRECT-URI' \
-F 'code=CODE' \https://api.instagram.com/oauth/access_token
I use ASP.NET so I found this equivalent OAuth 2.0 In .NET With Instagram API:
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", "ssdfsdfsdfsdfsdf");
parameters.Add("client_secret", "sdsdfdsfsdfsdfsdfsdfsdf");
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", "http://localhost:2422/LoginsGuests/GetLoginPage");
parameters.Add("code", code);
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", parameters);
var response = System.Text.Encoding.Default.GetString(result);
However I keep getting:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
What I am i doing wrong?
Almost there the instagram api expects a POST not a GET.
Add the "POST" parameter.
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
Also check the instagram settings -> redirect url.
Then this may help don't forget to add a reference to Newtonsoft.Json. Is in .Net version 4.5.1:
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
namespace Instagram
{
public class InstagramClient
{
public InstagramClient(string code)
{
GetToken(code);
}
private void GetToken(string code)
{
using (var wb = new WebClient())
{
var parameters = new NameValueCollection
{
{"client_id", "ClientId"},
{"client_secret", "ClientSecret"},
{"grant_type", "authorization_code"},
{"redirect_uri", "RedirectUri"},
{"code", code}
};
var response = wb.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
string json = Encoding.ASCII.GetString(response);
try
{
var OauthResponse = (InstagramOAuthResponse) Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(InstagramOAuthResponse));
}
catch (Exception ex)
{
//handle ex if needed.
}
}
}
public class InstagramOAuthResponse
{
public string access_token { get; set; }
public User user { get; set; }
}
public class User : System.Security.Principal.IIdentity
{
public string username { get; set; }
public string website { get; set; }
public string profile_picture { get; set; }
public string full_name { get; set; }
public string bio { get; set; }
public string id { get; set; }
public string OAuthToken { get; set; }
public string AuthenticationType
{
get { return "Instagram"; }
}
public bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(id); }
}
public string Name
{
get
{
return String.IsNullOrEmpty(full_name) ? "unknown" : full_name;
}
}
}
}
}
If you prefer HttpWebRequest class:
var request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/access_token/");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var requestDetails = "client_id=" + AppConfig.InstagramClientId;
requestDetails += "&client_secret=" + AppConfig.InstagramClientSecret;
requestDetails += "&grant_type=authorization_code";
requestDetails += "&redirect_uri=" + redirectUrl;
requestDetails += "&code=" + exchangeCode;
byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
request.ContentLength = bytes.Length;
using (Stream outputStream = request.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
var response = request.GetResponse();
var code = ((HttpWebResponse)response).StatusCode;
if (code == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var jsonString = streamReader.ReadToEnd();
var accessToken = ParseAccessToken(jsonString);
return accessToken;
}
}
Related
I am working on a requirement where I need to create multiple issues in one go by Using the REST API. However, I start with uploading a single issue because I am new in API integration. I write few lines of code in c#. Here is my code:
static void Main(string[] args)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
JiraCreateIssueRequest jcir = new JiraCreateIssueRequest();
//////////////////////////////////////////////////////////////////
string sUsername = "aaa#xyz.com";
string sPassword = "TestPassword";
string uri = #"https://domain.atlassian.net/rest/api/2/issue";
Uri address = new Uri(uri);
HttpWebRequest request;
//HttpWebResponse response = null;
StreamReader sr;
string sData = null;
string returnXML = string.Empty;
if (address == null) { throw new ArgumentNullException("address"); }
//jcir.project.ID = 100;
//jcir.Summary = "This issue is created by JIRA REST Api";
//jcir.Description = "This issue is created by JIRA REST Api";
//jcir.IssueType.ID = 1;
sData = #"{""fields"":{""project"":{""key"": ""SITT""},""summary"": ""REST API Uploading"",""description"":""Creating an issue via REST API"",""issuetype"": {""name"": ""Test""}}}";
//sData = jcir.ToString();
try
{
// Create and initialize the web request
request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
// Add the Authorization header to the web request
request.Credentials = new NetworkCredential(sUsername, sPassword);
//Write Data
if (sData != null)
{
byte[] byteData = UTF8Encoding.UTF8.GetBytes(sData);
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
}
}
}
catch (WebException wex)
{
// This exception will be raised if the server didn't return 200 - OK
// Try to retrieve more information about the error
if (wex.Response != null)
{
using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
{
try
{
string sError = string.Format("The server returned '{0}' with the status code {1} ({2:d}).",
errorResponse.StatusDescription, errorResponse.StatusCode,
errorResponse.StatusCode);
sr = new StreamReader(errorResponse.GetResponseStream(), Encoding.UTF8);
returnXML = sr.ReadToEnd();
}
finally
{
if (errorResponse != null) errorResponse.Close();
}
}
}
else
{
throw new Exception(wex.Message);
}
}
}
public class JiraCreateIssueRequest
{
protected JavaScriptSerializer jss = new JavaScriptSerializer();
public JiraProject project = new JiraProject();
public string Summary { get; set; }
public string Description { get; set; }
public JiraIssueType IssueType = new JiraIssueType();
public override string ToString()
{
return jss.Serialize(this);
}
}
public class JiraCreateIssueResponse
{
}
public class JiraProject
{
public int ID { get; set; }
//public string Key { get; set; }
}
public class JiraIssueType
{
public int ID { get; set; }
//public string Name { get; set; }
}
But when I am running the above code, I am getting the '400' error. I googled it and found that this usually this error comes when the URL or the Username/Password are incorrect. I cross checked both the things however its correct.
May I know why this error is coming or what will be the resolution of the problem?
Your password is not your login password, it's an API token that you get from here:
https://id.atlassian.com/manage/api-tokens
Generate a token, then use that as your password.
I have this json value that I want to convert to a List
[{
"id_cuenta": 1,
"nombre": "Mercedes Luj\u00e1n",
"apellido": "Llano",
"ci": 123,
"telefono": 123456789,
"dispositivo_id": "355790037549877",
"password": "holaa",
"created_at": "2016-07-02 11:36:57",
"updated_at": "2016-07-09 09:56:53"
}]
This is my code so far:
private List<cuentaObtener> mCuenta;
btnLogIn.Click += async(object sender, EventArgs e) =>
{
string url = "http://localhost:8000/api/v1/cuenta_ci/" + ci.Text + "";
JsonValue json = await ObtenerCi(url);
private async Task<JsonValue> ObtenerCi(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
//Code to convert JsonObject to List<T>
// Return the JSON document:
return jsonDoc;
}
}
This is my class where I want to store values:
public class cuentaObtener
{
public int id_cuenta { get; set; }
public string nombre { get; set; }
public string apellido { get; set; }
public int ci { get; set; }
public int telefono { get; set; }
public string dispositivo_id { get; set; }
public string password { get; set; }
}
How can I achieve this? Thank you in advance!
You need to download this Nuget Package (Right Click Project > Manager Nuget Packages)
Then you can use :
string json = null;
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
json = stream.ReadToEnd();
}
List<cuentaObtener> JsonConvert.DeserializeObject<List<cuentaObtener>>(json);
If you're using HttpClient:
var response = await httpClient.GetAsync(url);
string json = await response.Content.ReadAsStringAsync();
List<cuentaObtener> JsonConvert.DeserializeObject<List<cuentaObtener>>(json);
I found some new APIs in Windows 10 Mobile device portal that allows to run applications on user phone .
you can launch this like to see the result : http://{PhoneIP}/api/app/packagemanager/packages
and there's another API to launch applications :
api/taskmanager/app
Starts a modern app
HTTP verb: POST
Parameters
appid : PRAID of app to start, hex64 encoded
package : Full name of the app package, hex64 encoded
I have this code to run applications but doesn't work any idea ?
public class PackageInfoToRun
{
public string appid { get; set; }
public string package { get; set; }
public string PackageFamilyName { get; set; }
}
public class PhoneInstalledPackages
{
public Installedpackage[] InstalledPackages { get; set; }
}
public class Installedpackage
{
public string Name { get; set; }
public string PackageFamilyName { get; set; }
public string PackageFullName { get; set; }
public int PackageOrigin { get; set; }
public string PackageRelativeId { get; set; }
public bool IsXAP { get; set; }
}
private static string Encode(string strn)
{
var toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(strn);
string appName64 = System.Convert.ToBase64String(toEncodeAsBytes);
appName64 = appName64.Replace(" ", "20%");
return appName64;
}
public async Task<PhoneInstalledPackages> GetInstalledApps()
{
// /api/app/packagemanager/packages
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://127.0.0.1/api/app/packagemanager/packages");
string res = "";
webrequest.Method = "GET";
try
{
using (var webresponse = await webrequest.GetResponseAsync())
using (StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream()))
{
res = loResponseStream.ReadToEnd();
}
var des = JsonConvert.DeserializeObject<PhoneInstalledPackages>(res);
return des;
}
catch (Exception ex)
{
return null;
}
}
public async Task<bool> RunAppAsync(string appid, string packagename)
{
HttpResponseMessage http = new HttpResponseMessage();
string str;
try
{
var package = new PackageInfoToRun()
{
appid = Encode(appid),
package = Encode(packagename)
};
using (HttpClient client = new HttpClient())
{
var serial = JsonConvert.SerializeObject(package);
http = await client.PostAsync("http://127.0.0.1/api/taskmanager/app", new StringContent(serial, Encoding.UTF8, "application/json"));
using (HttpResponseMessage response = http)
{
str = await response.Content.ReadAsStringAsync();
string retur = str;
if (retur.Contains("true"))
{
return true;
}
return false;
}
}
}
catch (Exception ex)
{
return false;
}
}
what's going wrong in my codes ? thanks :)
I used your code with small changes and it works for me.
now RunAppAsync looks like this. Don't forget to specify a PORT.
HttpClient client = new HttpClient();
var serial = JsonConvert.SerializeObject(package);
var result = await client.PostAsync(String.Format("http://127.0.0.1:*PORT*/api/taskmanager/app?appid={0}&package={1}", package.appid, package.package), new StringContent(serial));
Where the package is
var package = new PackageInfoToRun()
{
appid = Encode(app.PackageRelativeId),
package = Encode(app.PackageFullName),
};
And the app variable is an instance of InstalledPackage class.
I need to obtain several pieces of information from a tweet using the json twitter API.
The only source provided is a tweet link.
This solution requires no twitter authentication and only 1 library json.net (available in Nuget Package Manager)
So far:
The program is able to do a httprequest on the Twitter json API.
I can see a response in the stream
But I am not able to deserialize the json response into the class.
Where:
Place a breakpoint in line and You will see that json_data contains json.
MyTweet = JsonConvert.DeserializeObject(json_data);
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace parsejson
{
class Program
{
static void Main(string[] args)
{
try
{
Tweet MyTweet = new Tweet();
string url;
url = "https://api.twitter.com/1/statuses/oembed.json?url=https://twitter.com/katyperry/status/657469411700244480";
var json_data = string.Empty;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = WebRequestMethods.Http.Get;
req.Accept = "application/json";
req.ContentType = "applicaton/json;charset=utf-8";
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
json_data = sr.ReadToEnd();
MyTweet = JsonConvert.DeserializeObject<Tweet>(json_data);
var stext = MyTweet.text;
Console.ReadLine();
}
catch (Exception)
{
throw;
}
}
public class Tweet
{
public string created_at { get; set; }
public long id { get; set; }
public string id_str { get; set; }
public string text { get; set; }
public string source { get; set; }
}
}
}
I have following nested JSON:
{"Command":"helo",
"parameter" : {"Configured":false, "ApplicationString":"Something", "Hostname":"some",
"IPAddress":"0.0.0.0",
"UniqueID":"",
"Username":"me"}}
And I need to pass this string as JSON object to POST call to my web service in C#. Could anyone help me how to do this step?
Note: I am able to pass simple JSON like below:
var request = (HttpWebRequest)WebRequest.Create("http://localhost:8084");
request.ContentType = "text/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Command = "test",
name="pooja"
});
streamWriter.Write(json);
}
If I follow the same way to pass nested json like below :
string json = new JavaScriptSerializer().Serialize(new
{
Command = "test",
parameter = new JavaScriptSerializer().Serialize(new
{
Command = "test",
}),
});
I get below output :
{"Command":"test","parameter":"{\"Command\":\"test\"}"}
Let me know if you have any issues.
void Main()
{
CommandParamater exampleCommand = new CommandParamater
{
Command = "Foo",
Parameter = new Parameter
{
ApplicationString = "App String Foo",
Configured = true,
Hostname = "Bar",
IPAddress = "8.8.8.8",
UniqueID = Guid.NewGuid().ToString(),
Username = "FooBar"
}
};
string uri = "http://localhost:8084";
string data = JsonConvert.SerializeObject(exampleCommand);
Html htmlClient = new Html();
htmlClient.Post(uri, data, "application/json");
}
public class Html
{
public string Post(string uri, string data, string contentType)
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentType = contentType;
request.ContentLength = dataBytes.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(dataBytes, 0, dataBytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
public class Parameter
{
[JsonProperty("Configured")]
public bool Configured { get; set; }
[JsonProperty("ApplicationString")]
public string ApplicationString { get; set; }
[JsonProperty("Hostname")]
public string Hostname { get; set; }
[JsonProperty("IPAddress")]
public string IPAddress { get; set; }
[JsonProperty("UniqueID")]
public string UniqueID { get; set; }
[JsonProperty("Username")]
public string Username { get; set; }
}
public class CommandParamater
{
[JsonProperty("Command")]
public string Command { get; set; }
[JsonProperty("parameter")]
public Parameter Parameter { get; set; }
}
It may help you.
private string MakeRequest(string uri, string jsnPostData, string method)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
if (request != null)
{
request.Method = method;
request.Timeout = 2000000;
request.ContentType = "application/json";
request.KeepAlive = true;
byte[] data = Encoding.UTF8.GetBytes(jsnPostData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
return result;
}
else
return "";
}
catch (Exception ex)
{
Response.Write("<b>Error :</b>" + ex.Message + "</br>");
return "";
}
}