Upload File Without Multipart/Form-Data Using RestSharp - restsharp

Below, there is a POST Request Done With Standard HttpWebRequest , and HttpWebResponse. Basically it post binanry file with some parameters.
How Can I do The Same Thing With RestSharp ?
Source:
https://github.com/attdevsupport/ATT_APIPlatform_SampleApps/tree/master/RESTFul/SpeechCustom, ATT_APIPlatform_SampleApps/RESTFul/Speech/Csharp/app1/ ]
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(string.Empty+parEndPoint );
httpRequest.Headers.Add("Authorization", "Bearer " + parAccessToken);
httpRequest.Headers.Add("X-SpeechContext", parXspeechContext);
if (!string.IsNullOrEmpty(parXArgs))
{
httpRequest.Headers.Add("X-Arg", parXArgs);
}
string contentType = this.MapContentTypeFromExtension(Path.GetExtension(parSpeechFilePath));
httpRequest.ContentLength = binaryData.Length;
httpRequest.ContentType = contentType;
httpRequest.Accept = "application/json";
httpRequest.Method = "POST";
httpRequest.KeepAlive = true;
httpRequest.SendChunked = parChunked;
postStream = httpRequest.GetRequestStream();
postStream.Write(binaryData, 0, binaryData.Length);
postStream.Close();
HttpWebResponse speechResponse = (HttpWebResponse)httpRequest.GetResponse();

A simple upload example:
RestClient restClient = new RestClient("http://stackoverflow.com/");
RestRequest restRequest = new RestRequest("/images");
restRequest.RequestFormat = DataFormat.Json;
restRequest.Method = Method.POST;
restRequest.AddHeader("Authorization", "Authorization");
restRequest.AddHeader("Content-Type", "multipart/form-data");
restRequest.AddFile("content", imageFullPath);
var response = restClient.Execute(restRequest);

Related

The server committed a protocol violation. Section=ResponseStatusLine : Issue

I created ASP.NET core 6 API project and used JWT authentication for each API end point.
But while executing in some physical system works fine but some other physical system and server throws below error
The server committed a protocol violation. Section=ResponseStatusLine
Sample Code
var request = (HttpWebRequest)WebRequest.Create(endpoint);
var token = System.Threading.Tasks.Task.Run(async() => await new Token("URL", "username", "pwd"])).Result;
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "POST";
var postData = JsonConvert.SerializeObject(Details, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var data = Encoding.ASCII.GetBytes(postData);
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var responses = (HttpWebResponse)request.GetResponse();
Sample code based on HTTP Client
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), endpoint))
{
string token = SalesOperationAPIToken("url", "usertest", "pwd");
request.Headers.TryAddWithoutValidation("accept", "*/*");
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
string json = JsonConvert.SerializeObject(Details);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = httpClient.SendAsync(request).Result;
var responseMessage = response.Content.ReadAsStringAsync().Result;
}
}
I am not sure what configuration need to be changed to get this worked in all system.
Thanks in advance.

Google API Calendar OAUTH2 The remote server returned an error: (404) Not Found

async void GetEvent(string access_token) {
String serviceURL = "https://www.googleapis.com/calendar/v3/calendars/{email}/events";
String url = string.Format(serviceURL + "&key={0}&scope={1}", clientSecret, "https://www.googleapis.com/auth/calendar.events.readonly");
// sends the request
HttpWebRequest userinfoRequest = (HttpWebRequest)WebRequest.Create(url);
userinfoRequest.Method = "GET";
userinfoRequest.Headers.Add(string.Format("Authorization: Bearer {0}", access_token));
userinfoRequest.ContentType = "application/json";
userinfoRequest.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
userinfoRequest.UseDefaultCredentials = true;
userinfoRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
// gets the response
WebResponse userinfoResponse = await userinfoRequest.GetResponseAsync();
using (StreamReader userinfoResponseReader = new StreamReader(userinfoResponse.GetResponseStream())) {
// reads response body
string userinfoResponseText = await userinfoResponseReader.ReadToEndAsync();
output(userinfoResponseText);
}
}

login to aspx page from another site using httprequest

Using C# and ASP.NET I want to programmatically fill login detail on a web page (form) and then 'POST' those values. How do I do this?currently i am using below code but it not work it take me on same page.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/");
req.Method = "GET";
StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
// extract the viewstate value and build out POST data
string viewState = ExtractViewState(responseData);
string postData =
String.Format(
"__VIEWSTATE={0}&CenterCPH_tbUsername={1}&CenterCPH_tbPassword={2}&CenterCPH_btnSubmit=Login",
viewState, "9115308123", "12345678#A"
);
// have a cookie container ready to receive the forms auth cookie
CookieContainer cookies = new CookieContainer();
HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/login.aspx");
req2.Method = "POST";
req2.ContentType = "application/x-www-form-urlencoded";
req2.ContentLength = postData.Length;
req2.KeepAlive = true;
req2.CookieContainer = cookies;
req2.AllowAutoRedirect = false;
StreamWriter sout = new StreamWriter(req2.GetRequestStream());
sout.Write(postData);
sout.Flush();
sout.Close();
HttpWebResponse res = (HttpWebResponse)req2.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
HttpWebRequest req3 = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/Terminals/Default.aspx");
req3.CookieContainer = cookies;
res = (HttpWebResponse) req3.GetResponse();
sr = new StreamReader(res.GetResponseStream());
returnvalue = sr.ReadToEnd();
sr.Close();
return returnvalue;

Google API HTTP 401 - Token invalid - AuthSub token has wrong scope

I'm struggling with google api for a few days while sending a post request to Google sites API via C# application.
First I redeem the authorization code from google's servers by a GET request:
https://accounts.google.com/o/oauth2/auth?
scope=email%20profile&
state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.mydomain/myHome&
redirect_uri=http://localhost&
response_type=code&
client_id= // CLIENT ID here...
access_type=online&
approval_prompt=auto
In the redirect uri I got the authorization code which I use to claim the
access token:
string RequestUrl;
RequestUrl = "https://www.googleapis.com/oauth2/v3/token";
WebRequest request = WebRequest.Create(RequestUrl);
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "code=4/aPJAhLvlGLxw1fjKDCOpEQjfoVtNDZYq7FzvrziUero#&" +
"client_id=//cilent id here&" +
"client_secret=client secret here&" +
"redirect_uri=http://localhost&" +
"grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
The response containing the token looks like that:
{
"access_token": "ya29.pAGX8f4e0ZyBazzq5rxWVS6lL1jRyj0_GCog5UEO3FiGT2h4cj10jee4ziAoA09vHRoVejN5p7Iw",
"token_type": "Bearer",
"expires_in": 3600,
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjE2NWQ2MzcwZTgzOTI5YmE4Y2E4ZWU5OTMzZTExZjg2Yzg4YzAwNjUifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTA1OTc0NjQwMTUzNzU0NjU1MDE5IiwiYXpwIjoiOTkwMzUxMjA1MzY4LXBudGYxZXNtaXQ3a3Zlbmg5cnRvbW5pMmdhMmY0N2ZsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJuaXIuazFAaGFpZmFuZXQub3JnLmlsIiwiYXRfaGFzaCI6Imc5MU5wOVRYS2JUaVEzcFpTM2Ewa1EiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXVkIjoiOTkwMzUxMjA1MzY4LXBudGYxZXNtaXQ3a3Zlbmg5cnRvbW5pMmdhMmY0N2ZsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiaGQiOiJoYWlmYW5ldC5vcmcuaWwiLCJpYXQiOjE0MzU4MjI2ODAsImV4cCI6MTQzNTgyNjI4MH0.CeaQ8S3GG-yeAwqjU1ixdB7ro2SVKp2QdVTXNWl6196oJeQU1LFLpZ9FtrpNEGSDKHXrO5zx0ldE52RYw8TwMKILUqqCHLOewVJQMjZ6tiPzt-b-qeUta6Op4Z9HerwkMK2sofl88G-XZ6jKc7gk1gGPVcATBU7x0-QPRhQxmDUzP7zceVeoOtBD8g7liVHakK9sA5RNonGt-N6SvzECqhSLss7kDuXc4dStnENhyv_9oTIpvVsQplE-cJz7fDHC7mkW7BfwsgKBE8XbruBz5-o3AG5RVGyUTYqDaoq9qr3_NqckiRISUS127scaYwcYPE22Q8L_2AnpfJU0vuxo6g"
}
And the final step is to call the google api using the access_token
this way:
HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create("https://sites.google.com/feeds/site/mydomain");
req.ContentType = "application/atom+xml";
req.Host = "sites.google.com";
req.Method = "POST";
req.Headers["Gdata-version"] = "1.4";
req.Headers["Authorization"] = "Bearer ya29.pAGX8f4e0ZyBazzq5rxWVS6lL1jRyj0_GCog5UEO3FiGT2h4cj10jee4ziAoA09vHRoVejN5p7Iw";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("<entry xmlns='http://www.w3.org/2005/Atom' xmlns:sites='http://schemas.google.com/sites/2008'><title>Source Site</title><summary>A new site to hold memories</summary><sites:theme>slate</sites:theme></entry>");
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
using (System.Net.WebResponse resp = req.GetResponse())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
string i = sr.ReadToEnd().Trim();
}
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
But at the end of this step I get a 401 http error.
Token invalid - AuthSub token has wrong scope
What am I doing wrong?
Thanks in advance
you are authenticating your users using the following scopes
scope=email%20profile&
The Sites Data API uses the following scope: https://sites.google.com/feeds/.

Google Clound Messaging server C#

I want to send message to GCM and I receive unavailable with status 200. What am I doing wrong?
var GoogleAppID = "";
var DeviceID = "";
var request = WebRequest.Create("https://android.googleapis.com/gcm/send");
request.Method = "POST";
request.Headers.Add("Authorization", "key=" + GoogleAppID);
request.ContentType = "application/json";
var message = new Message();
message.registration_ids.Add(DeviceID);
message.data.Add("gcm_message", "12345");
var jsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(message);
byte[] byteArray = Encoding.UTF8.GetBytes(jsonMessage);
request.ContentLength = byteArray.Length;
var reqStream = request.GetRequestStream();
reqStream.Write(byteArray, 0, byteArray.Length);
var response = request.GetResponse();
var responseCode = ((HttpWebResponse)response).StatusCode;
if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
{
return "Unauthorized - need new token";
}
else if (!responseCode.Equals(HttpStatusCode.OK))
{
return "Response from web service isn't OK";
}
var responseStream = response.GetResponseStream();
var streamReader = new StreamReader(responseStream);
var responseContent = streamReader.ReadToEnd();
streamReader.Close();
No need to build your own library, github already has one. Use the following.
https://github.com/Redth/GCMSharp