I need to post data to server, and get compressed data back from it.
I am using windows phone 7 sdk.
I read that it can be done using SharpGIS or Coding4Fun toolkit.
They use WebClient (AFAIK).
can anyone help me?
Here's what I need to do-
Post data(XML) to url
Get compressed data (only GZip supported by server) in the form of xml string/stream
deserialise the xml data received
and the methods should be awaitable.
When I had to do this in wp7, I
Created a Portable Class Library project within my solution
Nuget the HTTP client library at https://www.nuget.org/packages/Microsoft.Net.Http (Install-Package Microsoft.Net.Http)
Nuget http://www.nuget.org/packages/Microsoft.Bcl.Async/ (Install-Package Microsoft.Bcl.Async ) and add to your PCL and UI solution
With in the portable class library
public class PostData
{
public async Task<T> TestMe<T>(XElement xml)
{
var client = new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip
| DecompressionMethods.Deflate
});
var response = await client.PostAsync("https://requestUri", CreateStringContent(xml));
var responseString = await response.RequestMessage.Content.ReadAsStringAsync();
//var responseStream = await response.RequestMessage.Content.ReadAsStreamAsync();
//var responseByte = await response.RequestMessage.Content.ReadAsByteArrayAsync();
return JsonConvert.DeserializeObject<T>(responseString);
}
private HttpContent CreateStringContent(XElement xml)
{
return new StringContent(xml.ToString(), System.Text.Encoding.UTF8, "application/xml");
}
}
WebClient and HttpWebRequest for C4F toolkit are supported. HttpClient doesn't exist without http client library currently in WP.
I don't use Windows 8, which means Windows Phone SDK is only on VS 2010, which doesn't support the Microsoft HttpClient.
There's a NuGet package Delay.GZipWebClient written by an MS dev that adds simple support for it. So far it's worked like a charm.
http://blogs.msdn.com/b/delay/archive/2012/04/19/quot-if-i-have-seen-further-it-is-by-standing-on-the-shoulders-of-giants-quot-an-alternate-implementation-of-http-gzip-decompression-for-windows-phone.aspx
Related
I am trying to build a .NET small app to predict images using my model that was trianed on AutoML.
But I am getting this error:
Cloud AutoML API has not been used in project 618104708054 before or
it is disabled. Enable it by visiting
https://console.developers.google.com/apis/api/automl.googleapis.com/overview?project=618104708054
then retry. If you enabled this API recently, wait a few minutes for
the action to propagate to our systems and retry
First - this is not the project I am using.
Second - If I go to the link with my real project id - it says to me that the api is working well.
My code look like these:
public static string SendPOST(string url, string json)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "Bearer GOOGLE_CLOUD_TOKEN");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
//var res = new JavaScriptSerializer().Deserialize<Response>(result);
//return res;
return result;
}
}
I will appriciate your help,
Thanks.
I finally succeded to make it, the only issue is that I needed to create a service account using the web console:
https://console.cloud.google.com/projectselector/iam-admin/serviceaccounts?supportedpurview=project&project=&folder=&organizationId=
And then to download the json key and push it via the gcloud command from my PC -
gcloud auth activate-service-account --key-file="[/PATH/TO/KEY/FILE.json]
I found the solution in this post:
"(403) Forbidden" when trying to send an image to my custom AutoML model via the REST API
I am writing a .net core(Standard 1.6) library that connects to my WebAPI. The WebApi requires a client certificate.
The .net core library is something being called from a Xamarin iOS app.
I cannot for the life of me send an HTTP request with a Client Certificate header.
I can use the library and post to the API with a client certificate from Visual Studio 2017 on a windows machine.
When I move the same project into my Xamarin iOS app using VS for Mac I get:
"Method Not Implemented" when setting the SslProtocol or adding the client certificate:
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificates.Add(new X509Certificate2(certificate));
Relevant libraries:
using System.Net;
using System.Net.Http;
using System.Security;
using System.Security.Cryptography.X509Certificates;
Any help would be greatly appreciated.
Alright, this took me quite a while but i was able to send a client certificate in a web request to use for client auth on our server.
First, as awesome as Xamarin and .netCore are, they are missing alot of the methods .net developers are used to. I was not able to build a crossplatform request that would work on both Android and ios such as the HttpWebRequest.
For ios, i created a custom class that inherits from:NSUrlConnectionDataDelegate
I then override the:
public override void WillSendRequestForAuthenticationChallenge(NSUrlConnection
connection, NSUrlAuthenticationChallenge challenge)
{
byte[] cert = System.IO.File.ReadAllBytes("clientCertificate.pfx");
NSUrlCredential credential = iSecurity.ImportPK12File(cert, "certPassword");
challenge.Sender.UseCredential(credential, challenge);
}
I then created a class that returns the credential:
//cert is a byte array of a .pfx file included in the resource file
//iSecurity Custom class
NSUrlCredential credential = iSecurity.ImportPK12File(cert, "certpassword");
public static NSUrlCredential ImportPK12File(byte[] fileBytes, string passPhrase)
{
var cert = new X509Certificate2(fileBytes, passPhrase);
var options = NSDictionary.FromObjectAndKey(NSObject.FromObject(passPhrase), SecImportExport.Passphrase);
NSDictionary[] importStatus;
SecStatusCode statusCode = SecImportExport.ImportPkcs12(fileBytes, options, out importStatus);
if(statusCode != SecStatusCode.Success){
throw new Exception("Error importing certificate. ");
}
NSObject obj = importStatus[0]["trust"];
IntPtr secTrustRef = obj.Handle;
var identityHandle = importStatus[0][SecImportExport.Identity];
var identity = new SecIdentity(identityHandle.Handle);
var certificate = new SecCertificate(cert.GetRawCertData());
SecCertificate[] certificates = { certificate };
return NSUrlCredential.FromIdentityCertificatesPersistance(identity, certificates, NSUrlCredentialPersistence.ForSession);
}
You may also be able to override this method and send the creds:
public override void ReceivedAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
{
base.ReceivedAuthenticationChallenge(connection, challenge);
}
And i may move it to there but in order to fire this off you create the delegate of your class that inherits from :NSUrlConnectionDataDelegate
and add this to your connection. Any request fired through this connection will override the method and pass the certificate.
I'm new to Xamarin.Forms But I'm okay with UI modules development But I need to config the Web service in the project. I preferred REST service, How can I manage rest service in Xamarin.Forms. I've existing service details from the native iOS application. Can you please help me to config the POST and GET service call in Xamarin.Forms. If you share the example of each POST and Get, It would be more helpful for me.
We have a detailed documentation to access the RESTful webservice to help you. You can find the documentation here: https://developer.xamarin.com/guides/xamarin-forms/web-services/consuming/rest/
Add HttpClient Nuget Package
And Json Package
Using below snippet to consume the REST web service.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://Host/Service.svc/");
string jsonData = #"{""Password"" : ""test#123"", ""UserId"" : ""$test#demo"", ""format"" : ""json""}";
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.PostAsync("login", content);
var result = response.Content.ReadAsStringAsync().Result;
if (result != "")
{
var sessionResponseJson = JsonConvert.DeserializeObject<sessionResponse>(result);
}
I'm trying to make a single automated test that tests for decompression. But I've read online that visual studio automatically decompresses rest responses.
What I have:
public Response<TResponse> ExecuteRequest(IRestRequest request)
{
var response = RestClient.Execute(request);
var responseDto = (response.StatusCode == HttpStatusCode.OK) ? DeserializeResponse(response.Content) : DeserializeErrorResponse(response.Content);
return responseDto;
}
Where the rest client is the basic RestSharp rest client. But this doesn't return anything about the statistic of the call.
TestRequest.AddHeader("Content-Encoding", "gzip")
Doesn't work either :P
The responses are compressed through fiddler, but is there a way to automate testing this?
I use WebClient for most of my requests from my WP7 app.
According to Google App Engine logs, the UserAgent is "NativeHost".
I would like to use appname, appversion + phone instead.
Is it possible to change this string when using a WebClient, or a GZip WebClient?
Okay, current working solution:
var headers = new WebHeaderCollection();
// http://dotnetbyexample.blogspot.fi/2011/03/easy-access-to-wmappmanifestxml-app.html
var am = new Util.AppManifest(); // gets appmanifest as per link above
var maker = Microsoft.Phone.Info.DeviceStatus.DeviceManufacturer;
var model = Microsoft.Phone.Info.DeviceStatus.DeviceName;
headers["user-agent"] = string.Format("{0} {1} {2} AppVersion {3}",
maker, model, "WP7.5", am.Version);
WebClient c = new WebClient();
c.Headers = headers;
Now, let's see how much info I can get on what make of phone the app is running on...
Yes, you will have to manually specify the UserAgent string on the WebClient class.
WebClient client = new WebClient ();
client.Headers.Add ("user-agent", "My App; V=2.1, PhoneType");
Obviously you will need to specify/derive the values you want to use in the UserAgent (AppName, Version and Phone).