I am having a issue in solving REST api call in windows phone application.
The situation is something :
I want to Pass two parameter named here "session_token" and "userid" as header in rest api call i am using the following code but the expected output is not matched with the postman out put (attached in screen shot)
I have the following code
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Connection);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-ype", "application/x-www-form-urlencoded");
client.DefaultRequestHeaders.TryAddWithoutValidation("session_token", "sdfsffsdfsdffsfsdfsdfsdfsdf");
client.DefaultRequestHeaders.TryAddWithoutValidation("userid", "sdfsdfsdfsdfsdfsdd");
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("changepasswordinput", "{\"oldpassword\":\"sdfsdfdf\",\"newpassword\":\"sdfsdfsdf\"}"));
HttpContent content = new FormUrlEncodedContent(postData);
HttpResponseMessage response = await client.PostAsync("changepassword", content);
if (response.IsSuccessStatusCode)
{
var outputstring = await response.Content.ReadAsStringAsync();
responseBaseClass = await response.Content.ReadAsAsync<ResponseBaseClass>();
}
}
Please tell me where i am doing wrong.
Thanks in advance.
You are doing it right, the headers are there. Just click on the Headers(2) tab in Postman on the first screenshot and you will see them.
Related
Hello Stackoverflow community. I hope someone here can help me!!
I'm trying to integrate with the Zoopla API that requires the post request to send the following customized content type. (I've got the certificate side of things working fine).
application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json
I've tried the following approaches without any success (they all result in the following error)
System.FormatException: 'The format of value 'application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json' is invalid.'
Initial approach was to set it within the content of the RequestMessage
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/listing/list"),
Method = HttpMethod.Post,
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json")
};
When that didn't work I tried to set it via the default headers (the client below is from the ClientFactory)
client.DefaultRequestHeaders.Add("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
My final attempt was to set it without validation
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
I've just tried something else which unfortunately didn't work
string header = "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json";
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(header));
I am well and truly stumped!! HELP!! :-)
Content-Type is set on the content, not in DefaultRequestHeaders. You may try using TryAddWithoutValidation on the request content:
var content = new StringContent("hello");
content.Headers.ContentType = null; // zero out default content type
content.Headers.TryAddWithoutValidation("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
var client = new HttpClient(); // note: use IHttpClientFactory in non-example code
var response = await client.PostAsync("https://postman-echo.com/post", content);
Console.WriteLine(response.StatusCode); // OK
Console.WriteLine(await response.Content.ReadAsStringAsync());
// {"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-6345b568-22cc353761f361483f2c3157","content-length":"5","content-type":"application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json"},"json":null,"url":"https://postman-echo.com/post"}
First time working with the Microsoft Graph API and ran into something I'm not too sure about.
I'm supposed to be building some proof of concept web app where I can basically view a business drive (or a site/group drive) from an application (with it's own identity) and upload/download files to it. However, I'm running into some issues with figuring out what I'm doing wrong.
I wrote some helper functions to help me get a token, but it just doesn't seem to work.
Here are the functions I wrote:
public static async Task<string> GetAccessToken() {
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(tokenUrl);
// We want the response to be JSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Build up the data to POST.
List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
postData.Add(new KeyValuePair<string, string>("client_id", clientId));
postData.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
postData.Add(new KeyValuePair<string, string>("scope", scope));
FormUrlEncodedContent requestBody = new FormUrlEncodedContent(postData);
//Request Token
var request = await client.PostAsync(tokenUrl, requestBody).ConfigureAwait(false);
var response = await request.Content.ReadAsStringAsync();
var responseData = JsonConvert.DeserializeObject(response);
//Return Token
return ((dynamic)responseData).access_token;
}
}
public static async Task<dynamic> GetSite(string accessToken) {
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Add the Authorization header with the AccessToken.
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
// create the URL string.
string url = string.Format("{0}sites/root/", baseUrl);
// make the request
HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
// parse the response and return the data.
string jsonString = await response.Content.ReadAsStringAsync();
object responseData = JsonConvert.DeserializeObject(jsonString);
return (dynamic)responseData;
}
}
Whenever I would try to get a site, it seems to not work properly. So I figured I could try out the requests in Postman to see if they would work there, but after setting up Postman for application API calls, the response I would usually get is something like this:
{
"error": {
"code": "generalException",
"message": "An unspecified error has occurred.",
"innerError": {
"date": "SomeTimeLateAtNight",
"request-id": "WhateverTheRequestIDis",
"client-request-id": "WhateverTheClientRequestIDis"
}
}
}
Am I doing something wrong here? In my App Registration, I have the API Permissions set to "Sites.ReadAll, Sites.ReadWriteAll", which I found from here. I ran my token through jwt.ms and found that my roles were set to:
"APIConnectors.ReadWrite.All", "Sites.Selected", "Directory.ReadWrite.All", "Sites.Read.All", "Sites.ReadWrite.All", "Sites.Manage.All", "Files.ReadWrite.All", "Directory.Read.All", "Files.Read.All", "APIConnectors.Read.All", "Sites.FullControl.All"
These should be what I need to read/write/view these right? So I'm left a bit confused.
Just for kicks, I tried doing my requests through the Microsoft Graph Explorer, but everything ends up working as expected. I also pulled the auth token from the Graph Explorer request I did, and shoved it into my Postman requests and it ended up working, which leads me to believe I screwed up something with the Azure Application API permissions somehow. Any recommendations on where to go from here? Not sure if I'm explaining clearly enough, but how should I fix it so that requests as the application get an actual result instead of that general exception I'm getting? (Since the application would download/upload as itself, without any other user logged in.)
I created a new Azure AD App for your code for a quick test, these are the permissions that I granted to my app,please make sure that you have clicked the "Grant admin consent for" button to finish the grant permission process:
My test code below, based on a console app:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace GraphAPITest
{
class Program
{
static void Main(string[] args)
{
var accessToken = GetAccessToken().GetAwaiter().GetResult();
Console.WriteLine(GetSite(accessToken).GetAwaiter().GetResult());
}
public static async Task<string> GetAccessToken()
{
using (var client = new HttpClient())
{
var clientId = "<app id>";
var clientSecret = "<secret>";
var tenant = "<your tenant name/id>";
var scope = #"https://graph.microsoft.com/.default";
var tokenUrl = #"https://login.microsoftonline.com/"+ tenant + "/oauth2/v2.0/token";
client.BaseAddress = new Uri(tokenUrl);
// We want the response to be JSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Build up the data to POST.
List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
postData.Add(new KeyValuePair<string, string>("client_id", clientId));
postData.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
postData.Add(new KeyValuePair<string, string>("scope", scope));
FormUrlEncodedContent requestBody = new FormUrlEncodedContent(postData);
//Request Token
var request = await client.PostAsync(tokenUrl, requestBody).ConfigureAwait(false);
var response = await request.Content.ReadAsStringAsync();
var responseData = JsonConvert.DeserializeObject(response);
//Return Token
return ((dynamic)responseData).access_token;
}
}
public static async Task<dynamic> GetSite(string accessToken)
{
using (var client = new HttpClient())
{
var baseUrl = "https://graph.microsoft.com/v1.0/";
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Add the Authorization header with the AccessToken.
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
// create the URL string.
string url = string.Format("{0}sites/root/", baseUrl);
// make the request
HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
// parse the response and return the data.
string jsonString = await response.Content.ReadAsStringAsync();
object responseData = JsonConvert.DeserializeObject(jsonString);
return (dynamic)responseData;
}
}
}
}
Result:
Let me know if you have any further questions.
Check for the permission type application or delegated.
If it is application permission, the status column for the respective permission - green
If you see a warning message - meaning that the Admin consent has not been granted. You will have to get the consent before using the app. This error is likely the case.
You may have added the necessary permissions but forgot to provide the 'admin consent' as identified by Satya. Additional I would recommend using the MSAL library from Microsoft to handle this flow like this https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-netcore-daemon
Considerably fewer lines of more readable code.
public async static Task<RootUserData> getUSerLoggedIn(string userName, string password)
{
RootUserData rootUserData = new RootUserData();
var url = URlConstants.LOGIN_URL;
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{userName}:{password}");
httpClient.DefaultRequestHeaders.Add("content-type", "application/json");
httpClient.DefaultRequestHeaders.Add("cache-control", "no-cache");
} ;
}
I am using above code to make one Service call. I have to pass userEmailAddress in body as plain as shown in Postman Picture. Can You Please help me How to achieve this?
No... Its in Plain Text
Set your content mime type to "text/plain":
httpClient.DefaultRequestHeaders.Add("content-type", "text/plain");
And post a string:
var response = await httpClient.PostAsync(url, new StringContent(userName));
Content-Type should not be added like that, It didn't work in my case, and gave a wrong response, instead
Pass content-Type like this -
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
I'm very new on this and I need some help. I'm trying to send a notification from my webapi to my app. To do this a need just send a post to the url("https://onesignal.com/api/v1/notifications") with some informations (Header from authorization and content-type). But when I send the post it takes a long and and I just get The operation timeout has been reached, no message errors that could help me. I tryed the code from onesignal's documentation from asp.net solutions but isn't worked for me. Anyone can help? Or just help how can I trace the error with my requisiton? After try the code from onesignal's documentation I decided use the following code(both codes had the same behavior):
using (var client = new HttpClient())
{
var url = new Uri("https://onesignal.com/api/v1/notifications");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "Rest ID");
var obj = new
{
app_id = "APP ID",
contents = new { en = "English Message" },
included_segments = new string[] { "All" }
};
var json = JsonConvert.SerializeObject(obj);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
}
For some reason is taking a long time to send a notification and return some response for me. So I increase the timeout to wait the response and don't get a task cancelled. Hope help someone.
So currently I get a list of images with ID's. When the user then clicks on it, it downloads and displays the image. Everything works, I just need a progress bar to show where it is currently at.
Current code:
var values = new Dictionary<string, string>
{
{ "myPost", "Data" },
};
var client = new System.Net.Http.HttpClient();
var content = new FormUrlEncodedContent(values);
client.DefaultRequestHeaders.Add("test", "header");
var response = await client.PostAsync("myScript.php", content);
var responseString = await response.Content.ReadAsStringAsync();
Since you are using UWP. I would suggest you use the HttpClient provided in Windows.Web.Http. This has post/put and get methods which also provides progress.
See HttpClient for more details specifically HttpProgress in HttpClient.
Hope this helps!