Thanks in advance.
We are working on an oAuth2 process and need some help. The requirement given is to POST to the server with form variables embedded, and expect a server response in JSON. The documentation has a similar sequence involving a GET request returning JSON and a very similar method grabs the response just fine. However, in this case it gives an object ref error saying the response is null. We are getting a 200 OK message from server with a content length of 1929, and it says content-type is application/json so I have every reason to believe the content is there somewhere.
public rsAccessToken Signup(string Code, string State, string redirect_uri)
{
HttpClient client = new HttpClient();
rsAccessToken rt = null;
HttpResponseMessage response = null;
client.BaseAddress = new Uri(URLtoken);
string grant_type = "authorization_code";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", clientid, secret));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URLtoken);
var parameters = new Dictionary<string, string> { { "grant_type", grant_type }, { "code", Code }, { "state", State }, { "redirect_uri", redirect_uri } };
var encodedContent = new FormUrlEncodedContent(parameters);
Task task = client.PostAsync(URLtoken, encodedContent)
.ContinueWith((taskwithresponse) =>
{
Task<string> jsonString = response.Content.ReadAsStringAsync();
jsonString.Wait();
rt = JsonConvert.DeserializeObject<rsAccessToken>(jsonString.Result);
});
task.Wait();
client.Dispose();
return rt;
}
the response captured at the taskwithresponse point is:
Id = 104, Status = RanToCompletion, Method = "{null}", Result = "StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:\r\n{\r\n Connection: keep-alive\r\n Date: Mon, 14 Sep 2020 14:41:55 GMT\r\n ETag: W/\"789-W2Me6TSLLmO4+fEmAtfH4YWXhxs\"\r\n Set-Cookie: TS0108eb76=0119a2687f0aa2133862c3de61eb2485030f83265a0e1bcb62403e1c777052fccfeacf2df6a14e78b161afc6a43cfc2622532765bc; Max-Age=900; Path=/\r\n Content-Length: 1929\r\n Content-Type: application/json; charset=utf-8\r\n}"
Appreciate the help.
The correct code is:
public rsAccessToken VeteranSignup(string Code, string State, string redirect_uri)
{
HttpClient client = new HttpClient();
rsAccessToken rt = null;
client.BaseAddress = new Uri(URLtoken);
string grant_type = "authorization_code";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", clientid, secret));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URLtoken);
var parameters = new Dictionary<string, string> { { "grant_type", grant_type }, { "code", Code }, { "state", State }, { "redirect_uri", redirect_uri } };
var encodedContent = new FormUrlEncodedContent(parameters);
Task task = client.PostAsync(URLtoken, encodedContent)
.ContinueWith((taskwithresponse) =>
{
Task<string> jsonString = taskwithresponse.Result.Content.ReadAsStringAsync();
jsonString.Wait();
rt = JsonConvert.DeserializeObject<rsAccessToken>(jsonString.Result);
});
task.Wait();
client.Dispose();
return rt;
}
You should use taskwithreponse
Also, you should use the pure aysnc chain. Don't make the aynsc call to sync call.
public async Task<rsAccessToken> Signup(string Code, string State, string redirect_uri)
{
using(HttpClient client = new HttpClient())
{
rsAccessToken rt = null;
client.BaseAddress = new Uri(URLtoken);
string grant_type = "authorization_code";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", clientid, secret));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var(HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URLtoken))
{
var parameters = new Dictionary<string, string> { { "grant_type", grant_type }, { "code", Code }, { "state", State }, { "redirect_uri", redirect_uri } };
var encodedContent = new FormUrlEncodedContent(parameters);
HttpResponseMessage response = await client.PostAsync(URLtoken, encodedContent)
var jsonString = await response.Content.ReadAsStringAsync();
rt = JsonConvert.DeserializeObject<rsAccessToken>(jsonString.Result);
}
return rt;
}
}
Related
I want to post my parameter with HttpClient .
what is the Content in httpclient request body? I wrote it int the body part and when I run the project I get Error.
my code is:
string baseAddress = "https://WebServiceAddress";
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
HttpRequestMessage bodyRequest = new HttpRequestMessage(HttpMethod.Post, baseAddress)
bodyRequest.Content = new StringContent(JsonConvert.SerializeObject(Prescriptionrequest), Encoding.UTF8, "application/json");
var responseApi = Client.PostAsync(baseAddress, bodyRequest.Content, new System.Threading.CancellationToken(false));
what should be the format of bodyRequest.Content?
Use this code:
HttpClient client = new HttpClient();
var dictionary = new Dictionary<string, string>
{
{ "parameter0", "value0" },
{ "parameter1", "value1" }
};
var content = new FormUrlEncodedContent(dictionary);
var response = await client.PostAsync("https://WebServiceAddress", content);
var responseString = await response.Content.ReadAsStringAsync();
class Program
{
public static async Task<bool> Post(string siteUrl, string requestUri, HttpContent content)
{
var credential = new System.Net.NetworkCredential(
"User",
"Pass",
"Domain");
using (var handler = new HttpClientHandler() { Credentials = credential, UseProxy = false })
{
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
var mediaType = new MediaTypeWithQualityHeaderValue("application/json");
mediaType.Parameters.Add(new NameValueHeaderValue("odata", "nometadata"));
client.DefaultRequestHeaders.Accept.Add(mediaType);
client.DefaultRequestHeaders.Add("X-RequestDigest", await GetRequestDigest());
string url = string.Format(requestUri, siteUrl);
HttpResponseMessage response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
return true;
}
}
}
static async Task Main(string[] args)
{
string domain = "xxxx";
string SiteUrl = "https://SITE/";
string issuesListById = "{0}_api/web/lists/GetByTitle('issues')/items?$filter=ID eq 1";
string taskListUrlById = "{0}_api/web/lists/GetByTitle('tasks')/items?$filter=ID eq 932";
var credentials = new NetworkCredential("User", "Pass", domain);
var handler = new HttpClientHandler { Credentials = credentials };
using (var http = new HttpClient(handler))
{
var stringContent = new StringContent("", Encoding.UTF8, "application/json");
http.DefaultRequestHeaders.Accept.Clear();
http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await http.GetAsync(string.Format(taskListUrlById, SiteUrl)).ConfigureAwait(false);
string jsonData = await response.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<Tasks>(jsonData);
var itemToEdit = obj.Value.First();
itemToEdit.Status = "Close";
var content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
var update = await Post(SiteUrl, taskListUrlById, content);
}
}
}
I am trying to update the status of a task in a SharePoint list to "Close", I am using the post method to send the content, I am receiving "bad request" in the post method... I am using REST to communicate with SharePoint on Premise any idea on what causing this problem? (the GetRequestDigest function is working well). if someone can help... Thanks in Advance.
string taskListUrlById = "{0}_api/web/lists/GetByTitle('tasks')/items(932)"; //932 is the ID of the item to update
string SiteUrl = "yoursite";
string url = string.Format(taskListUrlById, SiteUrl);
string content = "{ '__metadata': { 'type': 'SP.Data.TasksListItem' }, 'Status': 'Close'}";
var credential = new System.Net.NetworkCredential("username",
"Password",
"domain");
using (var handler = new HttpClientHandler() { Credentials = credential, UseProxy = false })
{
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Add("X-RequestDigest", await GetRequestDigest());
request.Headers.Add("X-HTTP-Method", "MERGE");
request.Headers.Add("IF-MATCH", "*");
HttpContent strContent = new StringContent(content);
strContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
strContent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));
request.Content = strContent;
var response = await client.SendAsync(request);
}
}
I am trying to send a json Object to SalesFroce using HttpClient, but this behaves Weirdly...
First i login in to Salesforce Via following code
var sendPaylod = new Dictionary<string, string>
{
{"grant_type","password"},
{"client_id",s_clientId},
{"client_secret",s_clientSecrate},
{"username",s_username},
{"password",s_password}
};
HttpClient auth = new HttpClient();
HttpContent content = new FormUrlEncodedContent(sendPaylod);
HttpResponseMessage response = await auth.PostAsync(s_tokenRequestEndpointUrl, content);
string msg = await response.Content.ReadAsStringAsync();
Console.WriteLine(msg);
string authToken = (String)jsonObj["access_token"];
Now I have got authToken as a bearer token to send data to salesFroce
I am doing that by Following
var obj = new { Director = "003e000001MQYjB",
CityName = "XXAA",
CityId = "000000",
RegionName = "India",
RegionId = "00000" };
string c_url = "URL to which data will sent";
var c_Obj = JsonConvert.SerializeObject(obj);
var c_content = new System.Net.Http.StringContent(c_Obj, Encoding.UTF8, "application/json");
HttpClient c_client = new HttpClient();
c_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization","Bearer "+authToken);
HttpContent c_content = new StringContent(c_Obj, Encoding.UTF8, "application/json");
c_content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var c_response = await c_client.PostAsync(c_url, content);
var c_msg = await c_response.Content.ReadAsStringAsync();
Now Am getting Following Response...
"status": "success",
"recordId": "",
"message": ""
If i Use Same Bearer Token in Postman and Send same Json Object I receive Following response.
"status": "success",
"recordId": "a16e0000002qV6aE",
"message": ""
Please Help in this matter.
Fix the next errors:
Change:
var c_response = await c_client.PostAsync(c_url, content);
to:
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
c_client.DefaultRequestHeaders.Accept.Add(contentType);
var c_response = await c_client.PostAsync(c_url, c_content);
var c_msg = await c_response.Content.ReadAsStringAsync();
var result =JsonConvert.DeserializeObject<your return class>(c_msg);
and change your authorization to:
c_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken );
My friend write API and sends such request to php
$response = $http->post('http://you-app.com/oauth/token',[
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => 'my-username',
'password' => 'my-password',
'scope' => '',
],
])
it`s my code (I work at xamarin.ios)
maybe i'm sending the wrong request. (just starting to learn http request)
using (HttpClient client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) })
{
//create my json
Request json_Request = new Request
{
Url = "http://my_url/oauth/token",
Form_params = new Params
{
Grant_Type = "password",
Client_ID = "my_client_id",
Client_Secret = "my client secret",
Username = "my username",
Password = "my password",
Scope = ""
}
};
HttpContent content = new StringContent(JsonConvert.SerializeObject(json_Request), Encoding.UTF8);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(new Uri("http://my_url/oauth/token"), content);
if (response.IsSuccessStatusCode)
{
var response_From_Server = await response.Content.ReadAsStreamAsync();
return null;
}
else
{
return null;
}
}
i'm use this and server send me 401 error)
var values = new Dictionary<string, string>
{
{"grant_type", "password"},
{"client_id", "client-id"},
{"client_secret", "client-secret"},
{"username", "my username"},
{"password", "my password"},
{"scope", ""},
};
request.Content = new FormUrlEncodedContent(values);
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await client.PostAsync("http://inv/oauth/token", request.Content);
The way you are creating the request is wrong. Pls see this post
https://stackoverflow.com/a/4015346/1184584
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
Code in Node.Js
var url = 'https://accounts.google.com/o/oauth2/token';
var params = {
client_id: req.body.clientId,
redirect_uri: req.body.redirectUri,
code: req.body.code,
grant_type: 'authorization_code',
client_secret: config.GOOGLE_SECRET
};
console.log(req.body.code);
request.post(url, {
json: true,
form: params
}, function (err, response, token) {
var accessToken = token.access_token;
)};
Code in Web Api
var clientd = new ClientD()
{
client_id = client_id,
redirect_uri = redirect_uri,
client_secret = client_secret,
code = code,
grant_type = grant_type
};
String url = "https://accounts.google.com/o/oauth2/token";
using (var client = new System.Net.Http.HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add
(new MediaTypeWithQualityHeaderValue("application/json"));
var json = Newtonsoft.Json.JsonConvert.SerializeObject(clientd);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var httpResponseMessage = await client.PostAsync(url, content);
if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
{
return httpResponseMessage.StatusCode.ToString();
}
else
{
return httpResponseMessage.StatusCode.ToString();
}
}
I have a code for google authentication in node.js which is working fine. When I try to re-write the code in a controller of wep-api I get a bad request error.
Where am I going wrong ? Any help ?
Note: The client-id's and other info are perfectly set in both the cases.