Best way to POST and GET Response from REST API'S - c#

I am doing post and get response using HttpClient to communicate with REST API as below:
public static string PostToAPI( string value)
{
var payload = new APIModel
{
CommandText = value
};
var stringPayload = JsonConvert.SerializeObject(payload);
var httpContent = new StringContent(stringPayload,Encoding.UTF8,"application/json");
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
HttpResponseMessage message=client.PostAsync("https://testAPI/test",httpContent).Result if (message.IsSuccessStatusCode)
{
string result = message.Content.ReadAsStringAsync().Result;
return result;
}
return string.Empty;
}
is there any other alternative or best way do it?

You can always use HttpWebRequest and HttpWebResponse. Try Below
try
{
var webAddr = "URL";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application";
httpWebRequest.Method = "POST";
string str = "request string";
httpWebRequest.Headers["Authorization"] = "";
httpWebRequest.Headers["TenantId"] = "";
httpWebRequest.Headers["Client-Type"] = "";
httpWebRequest.Headers["Protocol"] = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
Console.WriteLine(str);
streamWriter.Write(str);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine("result=" + result);
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}

Related

Authenticate SharePoint online REST API without user name and password

I am trying to build a console app that reads the data from SharePoint list.
But i dont want to pass the user credentials in order to authenticate, instead use the token. Is this possible?
I tried using the following code but i get forbidden error while trying to GetFormDigest
static void Main(string[] args)
{
string sConnStr = "https://sab/sites/DevT";
Uri oUri = null;
oUri = new Uri(sConnStr + "/_api/web/lists/getbytitle('sd')/GetItems");
string sResult = string.Empty;
string stringData = "{'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml':'<View><Query><Where><Eq><FieldRef Name =\"Title\"/><Value Type=\"Text\">HR</Value></Eq></Where></Query></View>'}}";
HttpWebRequest oWebRequest = (HttpWebRequest)WebRequest.Create(oUri);
oWebRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
oWebRequest.Method = "POST";
oWebRequest.Accept = "application/json;odata=verbose";
oWebRequest.ContentType = "application/json;odata=verbose";
oWebRequest.Headers.Add("X-RequestDigest", GetFormDigest());
oWebRequest.ContentLength = stringData.Length;
StreamWriter writer = new StreamWriter(oWebRequest.GetRequestStream());
writer.Write(stringData);
writer.Flush();
WebResponse wresp = oWebRequest.GetResponse();
using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
{
sResult = sr.ReadToEnd();
}
}
public static string GetFormDigest()
{
string sFormDigest = null;
string sConnStr = "https://sab/sites/DevT";
Uri oUri = null;
oUri = new Uri(sConnStr + "/_api/contextinfo");
HttpWebRequest oWebRequest = HttpWebRequest.Create(oUri) as HttpWebRequest;
oWebRequest.UseDefaultCredentials = true;
oWebRequest.Method = "POST";
oWebRequest.Accept = "application/json;odata=verbose";
oWebRequest.ContentLength = 0;
oWebRequest.ContentType = "application/json";
string sResult;
WebResponse sWebReponse = oWebRequest.GetResponse();
using (StreamReader sr = new StreamReader(sWebReponse.GetResponseStream()))
{
sResult = sr.ReadToEnd();
}
var jss = new JavaScriptSerializer();
var val = jss.Deserialize<Dictionary<string, object>>(sResult);
var d = val["d"] as Dictionary<string, object>;
var wi = d["GetContextWebInformation"] as Dictionary<string, object>;
sFormDigest = wi["FormDigestValue"].ToString();
return sFormDigest;
}
You could use Add-in authentication to access SharePoint data.
You could check my test demo below.
https://social.msdn.microsoft.com/Forums/office/en-US/d33f5818-f112-42fb-becf-3cf14ac5f940/app-only-token-issue-unauthorized-access?forum=appsforsharepoint

Making a post request to yobit api

I am trying to make a post request to yobit api in UWP platform,this codes are working for other platforms.Here are my codes-
public async Task<RootObject> sellLimitCode()
{
RootObject track = null;
try
{
string url = "https://yobit.net/tapi/";
string parameters = "method=Trade&pair=ltc_btc&type=buy&rate=1&amount=1&nonce=" + (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
String strMsg = "api secret";
var uriBytes = encoding.GetBytes(parameters);
var uriBytes1 = encoding.GetBytes(strMsg);
string str_alg_name = MacAlgorithmNames.HmacSha512;
MacAlgorithmProvider obj_mac_prov = MacAlgorithmProvider.OpenAlgorithm(str_alg_name);
IBuffer buff_msg = CryptographicBuffer.CreateFromByteArray(uriBytes);
IBuffer buff_key_material = CryptographicBuffer.CreateFromByteArray(uriBytes1);
CryptographicKey hmac_key = obj_mac_prov.CreateKey(buff_key_material);
IBuffer hmac = CryptographicEngine.Sign(hmac_key, buff_msg);
byte[] digest = hmac.ToArray();
string hashText = byteToString(digest);
StringBuilder hex1 = new StringBuilder(hashText.Length * 2);
foreach (byte b in digest)
{
hex1.AppendFormat("{0:x2}", b);
}
string sign1 = hex1.ToString();
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.Headers["Key"] = "api key";
httpWebRequest.Headers["Sign"] = sign1;
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{ }
return track;
}
But I am getting Success:0,invalid key,method or nonce.I have tried changing everything.Still not working.

C# HttpClient usage

I am trying to write the following code using HttpClient and async, but it's not able return data.
WebRequest request = WebRequest.Create("some_url");
request.Headers.Add("cookie", "some_cookie");
Stream objStream = request.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string sLine = "";
int i = 0;
while (sLine != null)
{
i++;
sLine = objReader.ReadLine();
if (sLine != null)
Console.WriteLine(sLine);
}
Here is what I tried.
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("cookie", "some_cookie");
using (var response = await client.GetAsync("some_url"))
{
string responseData = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseData);
}
}
Any help will be appreciated.
Edit: Here is the code that works for me using HttpClient.
var baseAddress = new Uri(baseUrl);
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var requestMessage = new HttpRequestMessage(HttpMethod.Get, queryString);
requestMessage.Headers.Add("cookie", cookie);
var response = client.SendAsync(requestMessage);
response.Wait();
var content = response.Result.Content.ReadAsStringAsync();
content.Wait();
Console.WriteLine(content.Result);
}
Thanks for all the help.
You are doing the async and await, but you are not waiting for response data to be returned or reached so the following snippet will do the job :
Try this code :
static async Task<string> HttpGetResponse()
{
WebRequest request = WebRequest.Create("some_url");
request.Headers.Add("cookie", "some_cookie");
string responseData;
Stream objStream = request.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string sLine = "";
int i = 0;
while (sLine != null)
{
i++;
sLine = objReader.ReadLine();
if (sLine != null)
Console.WriteLine(sLine);
}
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("cookie", "some_cookie");
using (var response = await client.GetAsync("some_url"))
{
responseData = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseData);
}
}
return responseData;
}
in main call it like this :
static void Main(string[] args)
{
Task<string> t = HttpGetResponse();
//Do alot of work
t.Wait();
string response = t.Result;
Console.WriteLine(response);
}
Hope this was useful.

Why this method is called twice and at the first time the return doesn't work?

A flash application uses AMF message format to call the method SyncAddressBook (c#),and in this method ,it calls other two WebApis using HttpWebRequest (post and get ).
But only when calling WebApi (the method SyncAddressBook ), the method can return to flash well, when calling WebApi (the method SyncAddressBook ), the method SyncAddressBook can not return to the one which called it (i didnot write this method here) ,instead, it return itself. and for the second time, the method SyncAddressBook returned with error to flash .
here is the method (I omit something)
public AMFGreetoAddressBookResult SyncAddressBook(AMFGreetoLogin loginArgs, AMFGreetoAddressBook addressBook)
{
var result = new ........
this.PostReceiversGroups(addressBook, accessKey);
this.GetReceivers(accessKey, out receivers);
result.ResultCode = true;
return result;
}
private Boolean PostReceiversGroups(AMFGreetoAddressBook addressBook, string accessKey)
{
Uri theUri = new Uri(athenaSiteUrl + "/api/receivers");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(theUri);
httpWebRequest.KeepAlive = false;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add(AuthenticationServiceCodeHeaderKey, AddressServiceAccessCode);
httpWebRequest.Headers.Add(uthenticationServiceAccessKeyHeaderKey, AddressServiceAccessKey);
httpWebRequest.Headers.Add(AuthenticationUserAccessKey, accessKey);
httpWebRequest.Host = theUri.Host;
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(addressBook);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(json);
httpWebRequest.ContentLength = bytes.Length;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Account acc = JsonConvert.DeserializeObject<Account>(result);
}
}
catch (Exception e)
{
throw new Exception("住所管理サービスの更新処理でエラーが発生しました。[PostReceiversGroups] :" + e);
}
return true;
}
private Boolean GetReceivers(string accessKey, out AMFGreetoReceiver[] receivers)
{
Uri theUri = new Uri(athenaSiteUrl + "/api/receivers");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(theUri);
httpWebRequest.KeepAlive = false;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Headers.Add(AuthenticationServiceCodeHeaderKey, AddressServiceAccessCode);
httpWebRequest.Headers.Add(uthenticationServiceAccessKeyHeaderKey, AddressServiceAccessKey);
httpWebRequest.Headers.Add(AuthenticationUserAccessKey, accessKey);
httpWebRequest.Host = theUri.Host;
receivers = null;
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
var ser = new JavaScriptSerializer();
receivers = ser.Deserialize<AMFGreetoReceiver[]>(result);
streamReader.Close();
httpResponse.Close();
}
}
catch (Exception e)
{
throw new Exception("Receivers取得処理でエラーが発生しました。[GetReceivers] :" + e);
}
return true;
}

oauth/token returns empty body

I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

Categories