c # desktop app error 401 How can I send the data - c#

I do not have a problem getting tokens in the desktop application I developed. But when I try to send data, I get a 401 error.
HttpWebRequest webRequest;
string requestParams = "";
webRequest = (HttpWebRequest)WebRequest.Create("url");
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Headers.Add("x-api-key", "112233");
webRequest.Headers.Add("AccessToken", token);
byte[] byteArray = Encoding.UTF8.GetBytes(req);
webRequest.ContentLength = byteArray.Length;
using (Stream requestStream = webRequest.GetRequestStream())
{
requestStream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = webRequest.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
StreamReader rdr = new StreamReader(responseStream, Encoding.UTF8);
string Json = rdr.ReadToEnd();
}
}

The problem is about setting the token. First, you need to be sure what your server wants as a token. You can try this for the Bearer token.
webRequest.Headers.Add("Authorization", "Bearer " + token);

For your program to work, you have to provide an actual URL, not just the string "url", in
webRequest = (HttpWebRequest)WebRequest.Create("url");

Post to api with c # windows form application. oauth2.0
using (var client1 = new HttpClient ())
{
client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token());
client1.DefaultRequestHeaders.Add("x-api-key", "xxxx");
var builder = new UriBuilder(new Uri("you - url"));
HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Post, builder.Uri);
request1.Content = new StringContent("{\"values\":" + JsonConvert.SerializeObject("you -data")+ "}", Encoding.UTF8, "application/json");
HttpResponseMessage response = await client1.SendAsync(request1);
};

Related

Convert HttpWebRequest to HttpClient with POST method

I try to convert HttpWebRequest to HttpClient but without success.
Can anybody help me?
It is my simple code with HttpWebRequest:
string url = "https://www.somesite.com/Service";
string postData = "text to send";
var data = Encoding.ASCII.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.Proxy = null;
request.AllowAutoRedirect = false;
request.UserAgent = "Mozilla/5.0";
request.ContentType = "text/x-gwt-rpc; charset=UTF-8";
request.Headers.Add("Cookie", SetCookie);//get it after login
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
I think you can convert you HttpWebRequest based code to HttpClient based like this:
string url = "https://www.somesite.com/Service";
string postData = "text to send";
var data = Encoding.ASCII.GetBytes(postData);
var content = new ByteArrayContent(data);
using var httpHandler = new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false };
using var client = new HttpClient(httpHandler);
client.DefaultRequestHeaders.Add("UserAgent","Mozilla/5.0");
client.DefaultRequestHeaders.Add("ContentType", "text/x-gwt-rpc; charset=UTF-8");
client.DefaultRequestHeaders.Add("Cookie", SetCookie);
using var requestMessage = new HttpRequestMessage(HttpMethod.Post, url) { Content = content };
var response = await client.SendAsync(requestMessage);
var responseText = await response.Content.ReadAsStringAsync();
Remarks:
Instead of writing the Request's Stream manually you can use the ByteArrayContent abstraction for this. (Related SO topic)
In order to set the cookie(s) manually you have to turn-off the default behaviour. You can do this via the HttpClientHandler's UseCookies. (Related SO topic)
To set the headers manually you can use the HttpClient's DefaultRequestHeaders (Related SO topic)
The counterpart of GetResponse is the SendAsync
Instead of reading the Response's Stream manually you can use the HttpContent's ReadAsStringAsync (Related SO topic)
UPDATE: Include OP's amended code
var content = new StringContent(postData, Encoding.UTF8, "text/x-gwt-rpc");
So, instead of ByteArrayContent StringContent is being used.

C# Binary File Post Request

I am dealing with a third-party API which insists on a binary File Upload request being formatted without a Content-Type header value of multipart/form-data, and with the following headers:
Content-Type: application/octet-stream
Content-Disposition: filename*=UTF-8''file.zip
HttpRequestMessage and HttpContent.Headers.ContentDisposition.DispositionType won't allow me to achieve this either because I can't set the values as desired or they set them automatically.
I accept that this API may not be following HTTP Standards but it's not mine and I have no influence over it.
My attempt which does not work
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.ExpectContinue = false;
FileStream fs = new FileStream(#"e:\dev\TestHalfB.docx", FileMode.Open);
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, <Uri>);
HttpContent fc = new StreamContent(fs);
var mpContent = new MultipartFormDataContent();
mpContent.Add(fc);
fc.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
req.Content = fc;
fc.Headers.ContentDisposition.DispositionType = "filename*=UTF-8''TestHalfB.docx";
using (var response = await client.SendAsync(req))
{
response.EnsureSuccessStatusCode();
var resp = await response.Content.ReadAsStringAsync();
}
fs.Close();
}
Does anyone know of a lower level API I could use or have any suggestions?
So the crux is how can I set the Content-Disposition header to the value I desire.
I had to switch to using WebRequest.
WebRequest request = WebRequest.Create("https://cloud.memsource.com/web/api2/v1/projects/{id}/jobs?token={token}");
request.Method = "POST";
byte[] byteArray = File.ReadAllBytes(#"E:\Dev\TestHalfB.docx");
request.ContentType = "application/octet-stream";
request.ContentLength = byteArray.Length;
request.Headers.Add("Content-Disposition", "filename*=UTF-8''TestHalfB.docx");
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
((HttpWebResponse)response).StatusDescription.Dump();
Could you please try this.
HttpContent fileStreamContent = new StreamContent(paramFileStream);
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent, "file1", "file1");
var response = client.PostAsync(actionUrl, formData).Result;
}
This should work for you (or at least get you started, since it's not tested):
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, <Uri>);
using (FileStream fs = new FileStream(#"e:\dev\TestHalfB.docx", FileMode.Open))
{
byte[] fb = new byte[(int)fs.Length]; // assumes your file size will fit into an int
await fs.ReadAsync(fb, 0, (int)fs.Length);
req.Content = new ByteArrayContent(fb);
req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
req.Content.Headers.ContentDisposition.FileNameStar = "UTF-8''TestHalfB.docx";
using (var response = await client.SendAsync(req))
{
response.EnsureSuccessStatusCode();
var resp = await response.Content.ReadAsStringAsync();
}
}

How can I convert curl request to WebRequest in C#?

I'm trying to convert curl request to WebRequest in C# but not able to get the response as it always returns 401 unauthorized error
Here is the working curl request:
curl -k -v https://api.demo.peertransfer.com/v1/transfers -H "Content-Type: application/json" -X POST -d "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}" -H "X-Peertransfer-Digest: zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI="
Output:
The result in the red box is what I need to get in WebRequest Response,
here is my C# code
private void testnewfunc()
{
string value = "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}";
var URI = new Uri("https://api.demo.peertransfer.com/v1/transfers");
byte[] data = System.Text.ASCIIEncoding.Default.GetBytes(value);
var requst = (HttpWebRequest)WebRequest.Create(URI);
requst.UserAgent = "curl/7.43.0";
requst.Method = "POST";
requst.KeepAlive = true;
requst.AllowAutoRedirect = true;
requst.ContentType = " application/json";
requst.ContentLength = data.Length;
// wc.Headers["Content-Type"] = "application/json";
requst.Accept = "*/*";
//Or any other encoding type.
string result = System.Convert.ToBase64String(data);
var uname = "hultdemo2015";
var pword = "gEejgC0GF8pCbI7C";
var creds = string.Format("{0}:{1}", uname, pword);
creds = Convert.ToBase64String(Encoding.ASCII.GetBytes(creds));
requst.Headers["Authorization"] = string.Format("{0} {1}", "Basic", creds);
requst.Headers["X-Peertransfer-Digest"] = string.Format("{0}", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
using (Stream stream = requst.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var httpResponse = (HttpWebResponse)requst.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
// return true;
}
}
Not sure what I'm making wrong in the WebRequest.
Here's my solution:
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
var message = new HttpRequestMessage(HttpMethod.Post, new Uri("https://api.demo.peertransfer.com/v1/transfers"));
message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
message.Headers.Add("X-Peertransfer-Digest", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
message.Content = new StringContent("{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}", Encoding.UTF8, "application/json");
var responseMessage = await client.SendAsync(message);
MessageBox.Show(string.Format("Status Code: {0}{1}Content-Type: {2}{1}Date: {3}{1}Location:{4}", responseMessage.StatusCode, Environment.NewLine, responseMessage.Content.Headers.ContentType, responseMessage.Headers.Date, responseMessage.Headers.Location));
And here's the response from the server (same as curl):
Version compatible with .Net 4.0
var data = "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}";
var request = (HttpWebRequest)WebRequest.Create(new Uri("https://api.demo.peertransfer.com/v1/transfers"));
request.Method = "POST";
request.AllowAutoRedirect = false;
request.Accept = "*/*";
request.Headers.Add("X-Peertransfer-Digest", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var reqStream = request.GetRequestStream())
using (var writer = new StreamWriter(reqStream))
{
writer.Write(data);
}
var response = request.GetResponse();
MessageBox.Show(response.Headers.ToString());
Make sure you include these using statements:
using System.IO;
using System.Net;
and these are the response headers from the server:

How to use WebRequest in c#

I'am trying to use example api call in below link please check link
http://sendloop.com/help/article/api-001/getting-started
My account is "code5" so i tried 2 codes to get systemDate.
1. Code
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
2.Code
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
But i don't know that i use correctly api by above codes ?
When i use above codes i don't see any data or anything.
How can i get and post api to Sendloop.And how can i use api by using WebRequest ?
I will use api first time in .net so
any help will be appreciated.
Thanks.
It looks like you need to post your API key to the endpoint when making requests. Otherwise, you will not be authenticated and it will return an empty response.
To send a POST request, you will need to do something like this:
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx";
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
string userAuthenticationURI =
"https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ originZip +
"&destinations="+ DestinationZip + "&units=imperial&language=en-
EN&sensor=false&key=Your API Key";
if (!string.IsNullOrEmpty(userAuthenticationURI))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
var responseString = new
StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(responseString);
}

get a userID of a facebook user with http request C# WPF

I'm trying to get the userID of a Facebook user, I already have the access_token and I use http request to do it. My simple problem is that : I want the user's id but my program just crash... I use WPF, C# Here is my little call :
var url = string.Format("https://graph.facebook.com/me?access_token=" + token + "&response_type=id");
var req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "'access_token='" + token;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
var stream = req.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
WebResponse response = req.GetResponse();
aTextBox.Text = ((HttpWebResponse)response).StatusDescription;
stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
Thanks!
Don't use Web Browser for this! You may use HttpWebRequest for that kind of things:
string url = "https://graph.facebook.com/me?access_token=" + token + "&response_type=id";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string responseData = readStream.ReadToEnd();

Categories