How to using RESTSHARP to connect HUAWEI HILINK - c#

I use this following code, to connect huawei hilink, but it always returns an error.
First I get the token and session via
http://192.168.8.1/api/webserver/SesTokInfo
Can you please help me fix the issue?
string resulta = PostAndGetHTML("http://192.168.8.1/api/webserver/SesTokInfo");
string tok = resulta.Substring(57, 32);
string ses = resulta.Substring(108, 128);
Postxml("http://192.168.8.1/api/user/login", tok, ses);
public string PostAndGetHTML(string targetURL)
{
string html = string.Empty;
string url = targetURL;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
return html;
}
public void Postxml(string destinationUrl, string token, string ses)
{
var client = new RestClient();
string rawXml = #"<?xml version=""1.0"" encoding=""utf-8""?><request><Username>admin</Username><Password>" + Base64Encode("admin") + #"</Password></request>";
client.BaseUrl = new Uri(destinationUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("__RequestVerificationToken", token);
request.AddCookie("cookie",ses);
request.Timeout = 3000;
request.ReadWriteTimeout = 3000;
request.AddParameter("text/html", rawXml, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
}

Related

how to add body in post request c# [duplicate]

This question already has answers here:
How to post JSON to a server using C#?
(15 answers)
Closed 1 year ago.
i, tried putting body in request but didn't actually worked,
in body i want to put which is in json format {"ClaimNo":"123123"}
i have used this as code:
string ClaimStatus_url = "https:xyz";
WebRequest request = WebRequest.Create(ClaimStatus_url);
request.ContentType = "application/json";
request.Method = "POST";
//request.Headers = "";// i used this for puting body in it but did not work
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string result = reader.ReadToEnd();
using System.Text;
using System.Text.Json;
namespace TestPostData;
public class Data
{
public int ClaimNo { get; set; }
}
public static class Program
{
public static void Main()
{
var postData = new Data
{
ClaimNo = 123123,
};
var client = new System.Net.Http.HttpClient();
var content = new StringContent(JsonSerializer.Serialize(postData), Encoding.UTF8, "application/json");
var response = client.PostAsync("https:xyz", content).Result;
}
}
That is an example of using HttpClient class that is now recommended to use instead WebRequest.
Try this, i hope it will work.
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I would start off by using RestSharp.
dotnet add package RestSharp
Then I would create a DTOS object with the contents that you want to send in the json:
public class DtosObject
{
public string ClaimNo {get; set;}
}
Then pass that in as the object (I would call the class something relevant to the data it contains). If you only are using ClaimNo you could also use a KeyValuePair like this:
var body = new KeyValuePair<string, string>("ClaimNo", "123123");
Then you can send requests like this:
public async Task<IRestResult> PostAsync(string url, object body)
{
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.Post);
request.AddJsonBody(body);
var response = await client.ExecuteAsync(request);
return response;
}
string ClaimStatus_url = "https://qms.xyz.in/FGClaimWsAPI/api/Common/FetchClaimdetails";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(ClaimStatus_url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"ClaimNo\":\""+ userProfile.ClaimNumber +"\"}";
//string json = "{\"ClaimNo\":\"CV010831\"}";
//await turnContext.SendActivityAsync(MessageFactory.Text(json, json), cancellationToken);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result1 = "" ;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
result1 = result.Substring(1, result.Length -2); // to bring response result in proper format
}
_claimstaus = GenrateJSON_Claim(result1);
This upper code worked

c# to get oauth2 token but get error (Remote server returns 400 Bad Request)

I am trying to use this C# to get oauth token from a website. But the below codes return '404 Bad Request' error. Is there anything wrong in my code? The website engineer says there should be a JSON file returned to show error details. How do I get that JSON file? What I can see is just 1 line error message in VS2012.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://xxxx.com/api/oauth/token");
webRequest.Method = "POST";
webRequest.AllowAutoRedirect = true;
//write the data to post request
String postData = "client_id=abc&client_secret=xxx&grant_type=client_credentials";
byte[] buffer = Encoding.Default.GetBytes(postData);
if (buffer != null)
{
webRequest.ContentLength = buffer.Length;
webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
}
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();
I used Postman to send a request and I can get the token in its response. How should I modify my C# codes to get the token?
Can you try like this
public (string, string, string, string) GetOAuth(string CliendId, string ClientSecret, string OAuthURl)
{
using (var httpClient = new HttpClient())
{
var creds = $"client_id={CliendId}&client_secret={ClientSecret}&grant_type=client_credentials";
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var content = new StringContent(creds, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = httpClient.PostAsync(OAuthURl, content).Result;
var jsonContent = response.Content.ReadAsStringAsync().Result;
var tokenObj = JsonConvert.DeserializeObject<dynamic>(jsonContent);
var access_token = tokenObj?.access_token;
var token_type = tokenObj?.token_type;
var expires_in = tokenObj?.expires_in;
var scope = tokenObj?.scope;
return (access_token, token_type, expires_in, scope);
}
}
private void HowTOUse()
{
string access_token, token_type, expires_in, scope;
(access_token, token_type, expires_in, scope) = GetOAuth("client_id", "client_secret", "oauthurl");
}
Try using like the below code hope this code will solve the problem
private void Button_Click_1(object sender, RoutedEventArgs e)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://xxxx.com/api/oauth/token");
webRequest.Method = "POST";
webRequest.AllowAutoRedirect = true;
//write the data to post request
String postData =
"client_id=abc&client_secret=xxx&grant_type=client_credentials";
//byte[] buffer = Encoding.Default.GetBytes(postData);
//add these lines
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(postData);
if (buffer != null)
{
webRequest.ContentLength = buffer.Length;
webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
}
try
{
using (HttpWebResponse response =
(HttpWebResponse)webRequest.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();
TokenModel dt = JsonConvert.DeserializeObject<TokenModel>
(strResponse);
token = dt.accessToken;
//Assign json Token values from strResponse to model tok_val
tok_val.accessToken = dt.accessToken;
tok_val.expires_in = dt.expires_in;
tok_val.RefreshToken = dt.RefreshToken;
tok_val.tokenType = dt.tokenType;
}
}
}
catch (WebException wex)
{
error = "Request Issue: " + wex.Message;
}
catch (Exception ex)
{
error = "Issue: " + ex.Message;
}

Decode response from the server which based on (HttpWebResponse)

I have some problem with decoding the answer using the HttpWebrequest. When i authenticated in the server, i want to get the html code of the page. But get the:
‹?????­YлrЫЖ~h“Ж#D‚¤-ЫAKkQ¶2–м±h;©ДhVА‚ШPм‚”МСLях:У·hчOЯ&УѕFПо .”­(хLн№|зІзњ] ы[o_N~z761‡ыщ/%ЮpNІHєфП[ф2ЋЌDwr“Pdёz…‘ Чў'7 )§gВпоў^‘9Е(Ґ‘GSљV—фтЉ‰R®jкЗо‡Qчe<O€—aХЪСSoFиF—IњЉЉ ‹$мr—„м~'г4UKђ8Љ~њО‰иzTPW°8Є…Т$€#©ХЎsВBщсRКyHtN»nЖХhїйчww]WК†,є2R‚“®ґ¤Фыd!—6ь C#ЋЃ='3Ъ»о*1PL„tш‰u™с‰^§4]Рtї§йWѓqqRЫеiCjНJUѕ№›ІD<uЃЈю¶б…QµџїђС4Ьпйїкz—ЏwЈЯ¤u‡њџE*Э†ЬГГ,OЭ”ТИф¬Х‚¤ЕћнЕn6‡$ЋC*уMj§P*”©Б•†µЪ#4-з–†њJgОЯoТЪ#nиЕџ+§kЕ
фє¦®сЌКw°¤юm™—D.
лiП¦Ч¬E“RuГѓЗ-щ&­Ў~Щ°­”ЪдєћЋj“кfN=\Ж[Ўў‡П"кЎ-,k(ц
йьЪсј,¬•_’рF зцN<я+hюoА‚U#Ї{Uе}C'л€Я Фpneїш›kAл…10цЊѕ“R‘ҐpµTs…г3DduZъ1<–Мgрр™Б#Ње/сж,‚g–фІd–ЏВb–1х$ љ:лjХГо"Њ‰gІўЃ•±36uаlpгшЉQIк°Ћ1иГ?ЛщЦD…ІџВE–-§ЭF¶<Zђі®#№€ИВФр>†ЬyJJ тйoa„4/d0KЂtz'±G№УЮ”2М‘ґVрc3Aзаён†„у5НQћ1†
Жих[0c9ҐBRS аж‚"ТeJ"мІ(ўйлЙс|‘‡ѕќXаBи©#ЄА—LёБG… Yп‡|Z–сbГ(ё{­IZp*IњQ±” aK)^j?1OЦ*Ї–З№5КNПA›Г2БаQєЏ°s›Л†џAЫПЧ”Н±СQНєї§
Ё{I—ѕ>лч+О’LДp%џi^њБз8w?язжћЋ«0o}MрOBrѓуў>ЫйC…ЎЛ0vЇЊЏG}9*"т–€,MЕБІёvмыРќЪTwРW<ҐРиmЗН-JЫ(№®цx–x.]$љ™1l>\е&РJФэ1‚¦°І)&pЏ;€б*™H{-еЧыЦ‘:z'ьўД•?kD;ХBQkђGr’чќ_±ј…ЛУОГ»]т#йЌoWьсеХ}µЄМ[(Џ<S*кЇf=ЩfФТЩ_Ы\џ{е$—s*пў}и"лKЭ†dWU‹^ДіYH5И!+є3­ХбµP1KVчqEџtq/3¬ЫWБ^ҐђЂbMpD—ЖДЫґѕёE‹Бж№ч}ёЙzЦК
)I‹Ґ№f8UмВMёБ6©Љz‚ИЭ>ҐPF7a5[Ї¬нЃе\LL$eQ‡кµОD7рЇ{|Ьх<#цжу=x7ЄµsІ0Їѓґw ‘№
ћЏ~эxqxtrtъz|­кЩ!Tа­ѓ'ІЋdЪђQж:Р]ЪQyя0щv!›д¬?µ:•еjuUВг©UЁїЋі”йЙґ і(TТvJZ?9{:­&Xeж+YмT_WR\ж]ѕ•G№wаМЙЅИЯЇBИ9j'AЃѕ{{:Ѓ‡А!К»юц6пш8’WA\ZЙ'Ґ,DЬљ­ІйG
ЅЪ]т№UHЌ.Еуѕј{В)ЋВ,QЙ*ї:ШZЁќЦњS.Д›O"‚гв$’ођіёy©щRМaЊ†Љk’Ћў;
-МахЎq0J_Кі±zq*mе”{Ј№x-и¬Ъ{ъ#РeмЭч=¶0‡+зѕЎ.ј
Mб•?tхEµ>U‹ЃЭмЃЖ,…!ЛГ}’»XШ[Џd`КЏ\Ў' р рАХ0µOjЪA°ГтхDіЂvIТ®·Еч-‚а<Ђы’{6тi\ШН•е§.ЁЇНяnO›Э{бЂѓЋлыJ%ac>¤Ђ¬ЙE-куqуqСЅїЗЧ'mЬ'hx2ћGЈWГЬicо#!|џLЊ7oъґ
ъ
GЗG'|Ц|††ЮЅz?:?тyт9lТСџFп†ёЫFЬ…Ё]К№с.f‘hБцІpc;ЙуІЮO№%АgкUІх›юЅјA\КЇБ
еИИу•’ёЊSмхеDQЧ‹jЂеЧ!9µеr
иГLэїЉбя?бДЩЕъ??
Please help me to solve my problem< there is my code:
public static void RequestMutualAuths()
{
string logon = "admin";
string password = "admin";
string url = "http://192.168.1.55/";
WebRequest request = WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Accept-Language", "en-US");
request.Headers.Add("Accept-Encoding", "gzip, deflate");
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(logon + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.PreAuthenticate = true;
using (WebResponse response = request.GetResponse())
{
response.Headers.Add("Content-type", "text/plain");
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
using (Stream dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("windows-1251")))
{
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
}
}
}
class IrequesttoKness
{
public static void LoadHttpPageWithBasicAuthentication(string login, string password, RestClient url)
{
var client = url;
var request = new RestRequest(Method.GET);
request.AddHeader("Cache-Control", "no-cache");
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(login + ":" + password));
request.AddHeader("Authorization", "Basic" + credentials);
IRestResponse response = client.Execute(request);
var html = response.Content;
Console.WriteLine(html);
}
}

How to get OTCSticket with api/v1/auth method=post in content server using c#

Following is the API Call i make using postman and get a ticket back in the response body (screenshot):
I am not able to get the ticket in a HttpWebRequest Response in C#. Please below see the small sample code:
C# code
HttpWebRequest Request = WebRequest.Create(strUrl) as HttpWebRequest;
Request.Method = "POST";
Request.Headers.Add("Authorization", "Basic <>");
//Request.ContentType = "application/form-data";
Request.KeepAlive = true;
string data = string.Format("username=" + UserName + "&password=" + Password);
byte[] dataStream = Encoding.UTF8.GetBytes(data);
Request.ContentLength = dataStream.Length;
using (Stream newStream = Request.GetRequestStream())
{
// Send the data.
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
}
var Response = (HttpWebResponse)Request.GetResponse();
using (var stream = Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
if (Response.StatusCode != HttpStatusCode.OK)
throw new Exception("The request did not complete successfully and returned status code " + Response.StatusCode);
ResponseTicket strTicket= JsonConvert.DeserializeObject<ResponseTicket>(reader.ToString());
JsonConvert.DeserializeObject(Response.GetResponseStream().ToString());
MessageBox.Show(strTicket.Ticket);
}
Where as statuscode=200. But the content length is 0.
It is very difficult to find any meaning full help on CS10.5 API. I have checked there AppWorks platform but in vain. Would appreciate if someone can find the problem in the code, which apparently i can not see.
I don't know if this is still an issue for you. For me it was also, but figured it out:
public string LoginAsAdminAndRetrieveTicket(string userName, string passWord, string domain, string url)
{
var uri = $"http://{url}/otcs/llisapi.dll/api/v1/auth";
var request = new HttpRequestMessage();
request.Headers.Add("Connection", new[] { "Keep-Alive" });
request.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
request.Headers.Add("Pragma", "no-cache");
request.RequestUri = new Uri(uri);
request.Method = HttpMethod.Post;
request.Content = new StringContent($"username={userName};password={passWord}", Encoding.UTF8, "application/x-www-form-urlencoded");
var httpClientHandler = new HttpClientHandler
{
Proxy = WebRequest.GetSystemWebProxy(),
UseProxy = true,
AllowAutoRedirect = true
};
using (var client = new HttpClient(httpClientHandler))
{
var response = client.SendAsync(request).Result;
string ticket;
var vals = response.Headers.TryGetValues("OTCSTicket", out IEnumerable<string> temp) ? temp : new List<string>();
if (vals.Any())
{
ticket = vals.First();
}
return response.Content.ReadAsStringAsync().Result;
}
}

Get Access Token Using C#, Windows phone 8.1

I am trying to get the access token for the feed.Below is a code, i used to get the access token.
public async Task<string> GetAccessToken()
{
string postString = String.Format("username={0}&password={1}&grant_type=password", "userName", "pwd");
string url = "http://example.net/Token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
try
{
HttpWebResponse webResponse = (HttpWebResponse)(await request.GetResponseAsync());
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
string result = responseStreamReader.ReadToEnd();//parse token from result
}
catch(Exception ex)
{
}
return "";
}
The error below
"An error occurred while sending the request. The text associated with this error code could not be found.
The server name or address could not be resolved"
is throwing while it executes the below code
HttpWebResponse webResponse = (HttpWebResponse)(await request.GetResponseAsync());
Please help me to solve the issue
Try this if you are using POST request
public async Task<string> GetAccessToken()
{
string postString = String.Format("username={0}&password={1}&grant_type=password", "userName", "pwd");
try
{
using (var httpClient = new HttpClient())
{
var request1 = new HttpRequestMessage(HttpMethod.Post, "FeedURL");
request1.Content = new StringContent(postString);
var response = await httpClient.SendAsync(request1);
var result1 = await response.Content.ReadAsStringAsync();
result1 = Regex.Replace(result1, "<[^>]+>", string.Empty);
var rootObject1 = JObject.Parse(result1);
string accessToken = rootObject1["access_token"].ToString();
}
}
catch (Exception ex)
{
}
}

Categories

Resources