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);
}
}
Related
So I am using the Dailymotion API for uploading the video and use the code I get from the GitHub and it works perfectly but after 4 videos it gives the exception:
{"The remote server returned an error: (403) Forbidden."}
And I am getting an error in PublishVideo method
var response = request.GetResponse();
Main Code
var accessToken = GetAccessToken();
Authorize(accessToken);
Console.WriteLine("Access token is " + accessToken);
var fileToUpload = #"E:\Courses\[FreeCourseSite.com] Udemy - Entity Framework in Depth The Complete Guide\3. Building a Model using Database-First Workflow\11. Summary.mp4";
Console.WriteLine("File to upload is " + fileToUpload);
var uploadUrl = GetFileUploadUrl(accessToken);
Console.WriteLine("Posting to " + uploadUrl);
var response = GetFileUploadResponse(fileToUpload, accessToken, uploadUrl);
Console.WriteLine("Response:\n");
Console.WriteLine(response + "\n");
Console.WriteLine("Publishing video.\n");
var uploadedResponse = PublishVideo(response, accessToken);
Console.WriteLine(uploadedResponse);
Console.WriteLine("Done. Press enter to exit.");
Console.ReadLine();
}
private static UploadResponse GetFileUploadResponse(string fileToUpload, string accessToken, string uploadUrl)
{
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var responseBytes = client.UploadFile(uploadUrl, fileToUpload);
var responseString = Encoding.UTF8.GetString(responseBytes);
var response = JsonConvert.DeserializeObject<UploadResponse>(responseString);
return response;
}
private static UploadedResponse PublishVideo(UploadResponse uploadResponse, string accessToken)
{
var request = WebRequest.Create("https://api.dailymotion.com/me/videos?url=" + HttpUtility.UrlEncode(uploadResponse.url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", "OAuth " + accessToken);
var requestString = String.Format("title={0}&tags={1}&channel={2}&private={3}&published={4}",
HttpUtility.UrlEncode("123123123"),
HttpUtility.UrlEncode("tag1"),
HttpUtility.UrlEncode("news"),
HttpUtility.UrlEncode("true"),
HttpUtility.UrlEncode("true"));
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var uploadedResponse = JsonConvert.DeserializeObject<UploadedResponse>(responseString);
return uploadedResponse;
}
private static string GetAccessToken()
{
var request = WebRequest.Create("https://api.dailymotion.com/oauth/token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var requestString = String.Format("grant_type=password&client_id={0}&client_secret={1}&username={2}&password={3}",
HttpUtility.UrlEncode(SettingsProvider.Key),
HttpUtility.UrlEncode(SettingsProvider.Secret),
HttpUtility.UrlEncode(SettingsProvider.Username),
HttpUtility.UrlEncode(SettingsProvider.Password));
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var oauthResponse = JsonConvert.DeserializeObject<OAuthResponse>(responseString);
return oauthResponse.access_token;
}
private static void Authorize(string accessToken)
{
var authorizeUrl = String.Format("https://api.dailymotion.com/oauth/authorize?response_type=code&client_id={0}&scope=read+write+manage_videos+delete&redirect_uri={1}",
HttpUtility.UrlEncode(SettingsProvider.Key),
HttpUtility.UrlEncode(SettingsProvider.CallbackUrl));
Console.WriteLine("We need permissions to upload. Press enter to open web browser.");
Console.ReadLine();
Process.Start(authorizeUrl);
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
Console.WriteLine("Press enter once you have authenticated and been redirected to your callback URL");
Console.ReadLine();
}
private static string GetFileUploadUrl(string accessToken)
{
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var urlResponse = client.DownloadString("https://api.dailymotion.com/file/upload");
var response = JsonConvert.DeserializeObject<UploadRequestResponse>(urlResponse).upload_url;
return response;
}
}
It could be related to many causes. I suggest you to catch the error and get the response stream from our API:
try{
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var uploadedResponse = JsonConvert.DeserializeObject<UploadedResponse>(responseString);
return uploadedResponse;
}
catch(WebException e){
var rs = e.Response.GetResponseStream();
string errorResponseString;
using (var reader = new StreamReader(rs))
{
errorResponseString = reader.ReadToEnd();
}
Console.WriteLine(errorResponseString);
return null;
}
You will get a message explaining you why your access is forbidden.
I also invite you to check our API rate limit rules which can be a cause of forbidden call: https://developer.dailymotion.com/api/#rate-limit
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);
}
I have a library for 4.5 net fw. I need do the same but for net core.
Big beer for person which can repair this..
Code from VS with errors (screen)
MY code:
string returnData = String.Empty;
var webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Accept = "*/*";
webRequest.UserAgent = ".NET";
webRequest.Method = method;
webRequest.ContentType = "application/json";
webRequest.Host = "coinbase.com";
string nonce = Convert.ToInt64(DateTime.Now.Ticks).ToString();
string message = nonce + url;
string signature = HashEncode(HashHMAC(StringEncode(API_SECRET), StringEncode(message)));
var whc = new WebHeaderCollection();
whc.Add("ACCESS_KEY: " + API_KEY);
whc.Add("ACCESS_SIGNATURE: " + signature);
whc.Add("ACCESS_NONCE: " + nonce);
webRequest.Headers = whc;
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
returnData = reader.ReadToEnd();
}
}
}
You can use my code as below. Hope to help, my friend:
var webRequest = WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Accept = "*/*";
webRequest.UserAgent = ".NET";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.ContentType = "application/json";
webRequest.Host = "coinbase.com";
var whc = new WebHeaderCollection
{
"ACCESS_KEY: " + API_KEY,
"ACCESS_SIGNATURE: " + signature,
"ACCESS_NONCE: " + nonce
};
webRequest.Headers = whc;
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
returnData = reader.ReadToEnd();
}
}
}
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;
}
}
I need to call a method from a webservice, so I've written this code:
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.
webRequest.ContentLength = 0;
WebResponse webResponse = webRequest.GetResponse();
But this method requires some parameters, as following:
Post data:
_username:'API USER', // api authentication username
_password:'API PASSWORD', // api authentication password
How can I add these parameters into this Webrequest?
Use stream to write content to webrequest
string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.
If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:
private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri)
{
var result = "";
if (!string.IsNullOrEmpty(requestUri))
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request != null)
{
request.KeepAlive = true;
var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.CachePolicy = cachePolicy;
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
request.Timeout = Constants.RequestTimeOut;
if (request.Method == "POST")
{
if (postData != null)
{
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}
}
}
using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null)
{
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
}
}
responseUri = null;
return null;
}
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()