POST request in WP8 app - vb.net

I'm creating a VB.NET app for Windows Phone 8 and I'm currently looking for a solution to send a POST request to a page, and to get the response (simply knowing the page content).
I searched on several forums but none of them helped me.
Thank you in advance

Before u have to download this NuGet package HttpClient for Windows Phone and try this code:
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://www.google.com/");
var response = await httpClient.SendAsync(request);
var result = response.Content.ReadAsStringAsync().Result;
This will help you.
And u have to use in async method try this.
Async Function AccessTheWebAsync() As Task(Of Integer)
Dim client As HttpClient = New HttpClient()
Dim getStringTask As Task(Of String) = client.GetStringAsync("http://google.com")
Dim urlContents As String = Await getStringTask
Return urlContents.Length
End Function

Related

How to get microsoft account profile photo after login with application in mvc

With the help of claimprincipal, I'm able to get the details of signedin user as below but its not giving any pic related information as google does:
https://apis.live.net/v5.0/{USER_ID}/picture?type=large
which says The URL contains the path '{user_id}', which isn't supported.
Even tried
https://graph.microsoft.com/v1.0/me/photo/$value
which is asking for access token, but I am not sure what have to be passed
string userName = ClaimsPrincipal.Current.FindFirst("name").Value;
string userEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
Wanted an image which was added in any outlook account
For Image to show.. We have to use beared token and have to convert the image into memory stream and then have to used it.. I have done it in below ways. Hope this help ...
var client = new RestClient("https://login.microsoftonline.com/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"code={code}&client_id={OutClientId}&client_secret={SecretKey}&redirect_uri={OutRedirectUrl}&grant_type=authorization_code", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Token jsonContent = JsonConvert.DeserializeObject<Token>(response.Content);
var Token = jsonContent.AccessToken;
var TokenType = jsonContent.TokenType;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
HttpResponseMessage response1 = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photos/96x96/$value");
if (response1.StatusCode == HttpStatusCode.OK)
{
using (Stream responseStream = await response1.Content.ReadAsStreamAsync())
{
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
byte[] buffer = ms.ToArray();
string result = Convert.ToBase64String(buffer);
HttpContext.Session[AppConstants.UserImage] = String.Format("data:image/gif;base64,{0}", result);
responseStream.Close();
}
}
Is there any reason you are using the live.net apis? Instead of the Microsoft Graph APIs? Microsoft Graph APIs are the future for all user data within Microsoft 365 consumer and commercial accounts.
You can get the Users photo very easily as described here https://learn.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0
GET /me/photo/$value
As you are using ASP.NET MVC, there is an SDK you can use that makes this very easy too.
https://learn.microsoft.com/en-us/graph/sdks/sdks-overview?context=graph%2Fapi%2F1.0&view=graph-rest-1.0

Get string returned from a PostAsync event

I'm using HttpClient like this in my console app:
using (var http = new HttpClient(handler))
{
http.BaseAddress = new Uri("http://127.0.0.1:34323/");
var response = await http.PostAsync("/api/generate", new StringContent(
JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"));
Console.WriteLine(response.Content.ToString());
}
In debug mode, I can see that the controller is returning a string of JSON.
However, I only get this written to the console:
System.Net.Http.StreamContent
How can I get it to write the actual JSON that's being returned?
Thanks!
Try below line:
Console.WriteLine(response.Content.ReadAsStringAsync().Result.ToString());

RestSharp Returning Unauthorized

I am having an issue and think I may be missing something with RestSharp.
I am authorizing and getting back a cookie just fine... see below. But then when I call to get the data it returns unauthorized. It works just fine in Postman but not in the code below. I am using a console app and I have tried to send the cookie via AddHeader, AddCookie, and just as a parameter. The responseLogin does contain the correct cookie. Any help would be great.
Dim clientLogin = New RestClient("http://[URI to Authorize]............")
Dim requestLogin = New RestRequest(Method.POST)
requestLogin.AddParameter("application/x-www-form-urlencoded", "[Username and password here.....]", ParameterType.RequestBody)
Dim responseLogin As IRestResponse = clientLogin.Execute(requestLogin)
Dim client = New RestClient("http://[URI to get data]............")
Dim request = New RestRequest(Method.GET)
request.AddHeader("Cookie", responseLogin.Cookies(0).Value.ToString)
request.AddHeader("Accept", "application/json")
Dim response As IRestResponse = client.Execute(request)
The Cookie header needs to contain the name and value for the cookie, e.g.
Dim authCookie = responseLogin.Cookies(0) ' Probably should find by name
request.AddHeader("Cookie", String.Format("{0}={1}", authCookie.Name, authCookie.Value))
However, the documentation (I've never used RestSharp personally) says that RestSharp has automatic support for cookies, so if you reuse the RestClient instance and set the CookieContainer you shouldn't need to do anything to handle the cookies manually (unless you want to, which in some cases may be preferable).
Dim client = New RestClient(New Uri("[Base URI...]"))
client.CookieContainer = New System.Net.CookieContainer()
Dim requestLogin = New RestRequest("[login page path]", Method.POST)
requestLogin.AddParameter("application/x-www-form-urlencoded", "[Username and password here.....]", ParameterType.RequestBody)
Dim responseLogin As IRestResponse = client.Execute(requestLogin)
Dim request = New RestRequest("[data api path", Method.GET)
request.AddHeader("Accept", "application/json")
Dim response As IRestResponse = client.Execute(request)
You could probably just reuse the cookie container with different RestClient instances instead of reusing the client.
I had the same issue on RestClient .NET framework 4.5.2 version.
It turns out you have to implement the IAuthenticator interface.
public class MyAuth : IAuthenticator
{
readonly string _password;
readonly string _passwordKey;
readonly string _username;
readonly string _usernameKey;
public MyAuth(string usernameKey, string username, string passwordKey, string password)
{
_usernameKey = usernameKey;
_username = username;
_passwordKey = passwordKey;
_password = password;
}
public void Authenticate(IRestClient client, IRestRequest request)
=> request
.AddCookie(_usernameKey, _username)
.AddCookie(_passwordKey, _password);
//.AddParameter(_usernameKey, _username)
//.AddParameter(_passwordKey, _password);
}
I did this and my request worked.

How to read MultipartFormDataContent from HttpResponseMessage

I am creating a Web API application that returns multiple files to the user in a HttpResponseMessage. Below is a sample of the HttpResponseMessage object
Dim apple, banana As Byte()
apple = File.ReadAllBytes("some place")
banana = File.ReadAllBytes("some place")
Dim multiDataContent As New MultipartFormDataContent()
multiDataContent.Add(New ByteArrayContent(apple), "apple", "apple.xml")
multiDataContent.Add(New ByteArrayContent(banana), "banana", "banana.xsd")
Dim response As HttpResponseMessage = New HttpResponseMessage(HttpStatusCode.OK)
response.Content = multiDataContent
return response
My Question is how can I read the MultipartFormDataContent as the object returned to the client is a StreamContent (response.Content), how can I read the MultipartFormDataContent ?
Thanks in advance
see http://www.strathweb.com/2012/08/a-guide-to-asynchronous-file-uploads-in-asp-net-web-api-rtm/
Importantly do not forget to add System.Net.Http.Formatting to the project and "Imports System.Net.Http.Formatting" into the class so that you can use HttpContentMultipartExtensions.

Windows Phone VB Web Request

does anybody has an idea how I can perform an asynchronus Post Request in VB.Net for Windows Phone 8?
I tried a lot but nothing worked... also this http://msdn.microsoft.com/de-de/library/system.net.httpwebrequest.begingetrequeststream.aspx didn't work.
Thanks a lot.
I had to figure this out for myself a while ago. Let me see what I can do to help.
Posting a web request is actually simpler than that link shows. Here's what I do.
First, I create a MultipartFormDataContent:
Dim form as New MultipartFormDataContent()
Next, I add each string I want to send like this:
form.Add(New StringContent("String to sent"), "name of the string you are sending")
Next, create a HttpClient:
Dim httpClient as HttpClient = new HttpClient()
Next, we'll create a HttpResponseMessage and post your information to the url of your choice:
Dim response as HttpResponseMessage = Await httpClient.PostAsync("www.yoururl.com/wherever", form)
Then, I usually need the response as a string, so I read the response to a string:
Dim responseString as String = Await response.Content.ReadAsStringAsync()
This will give you the response you wanted, if that's what you wanted.
Here's an example of a method I use:
Public Async Function GetItems() As Task
Dim getUrl As String = "https://myapiurl.com/v3/get"
Dim responseText As String = String.Empty
Dim detailType As String = "complete"
Try
Dim httpClient As HttpClient = New HttpClient()
Dim form As New MultipartFormDataContent()
form.Add(New StringContent(roamingSettings.Values("ConsumerKey").ToString()), "consumer_key")
form.Add(New StringContent(roamingSettings.Values("access_token").ToString()), "access_token")
form.Add(New StringContent(detailType.ToString()), "detailType")
Dim response As HttpResponseMessage = Await httpClient.PostAsync(getUrl, form)
responseText = Await response.Content.ReadAsStringAsync()
Catch ex As Exception
End Try
End Function
If you aren't using the Http client libraries, you need to install them like this:
What you need to do to use the HttpClient, is to navigate in Visual Studio, go to Tools->Library Package Manager->Manage Nuget Packages for this solution. When there, search the online section for HttpClient and make sure you have "Include Prerelease" selected in the listbox above the results. (Default is set to "Stable Only")
Then install the package with the ID of Microsoft.Net.Http
Then you'll need to add an Import statement at the beginning of the document you are using it in.
Let me know if this is what you were looking for.
Thanks,
SonofNun