Xamarin Android Httppost Request - xamarin

I am trying to make a post call to my web Api which is on local host. But I am getting following error
result = {System.Net.WebException: The remote server returned an
error: (415) Unsupported Media Type. at
System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult
asyncResult) [0x0005e] in
/Users/builder/data/lanes/3511/f4db8a57/source/mono/mcs/class/System/Sy...
Can anyone help? Below is my code:
private void click (Object sender, EventArgs e)
{
UserInfo user = new UserInfo(1, "hellohello#gmail.com", "helloss");
String data = JsonConvert.SerializeObject(user);
WebClient wc = new WebClient();
wc.UploadStringAsync(new Uri("http://192.168.206.2:155/api/register"), data);
wc.UploadStringCompleted += Wc_UploadStringCompleted;
}
private void Wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var result = e.Error;
}

So far, the Server only get's a string from you and can't know if, it is json, xml or something else. You just have to tell him.
You can to this on a WebClient via:
wc.Add("Content-Type", "aplication/json");
If you are using the HttpClient you have to set ist via the Content property:
request.Content = new StringContent("json", Encoding.UTF8, "application/json");

The HTTP specification states:
415 Unsupported Media Type
The 415 (Unsupported Media Type) status code indicates that the origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method. The format problem might be due to the request's indicated Content- Type or Content-Encoding, or as a result of inspecting the data directly.
It seems your server is having troubles with the format... try adding the headers with .Add("Accept", "aplication/json");

Related

Sending gzipped data over HTTPS

I need to send a gzipped byte array over HTTPS. I searched the web and only thing ı can found is SharpGIS.GZipWebClient.
However, the problem is - this third party solution only works with WebClient which allow you to send only String data.
(I'm on Windows Phone 8. Most of the WebClient methods do not exist.)
Any ideas to solve this problem?
Edit:
This is how I tried the POST JSON data over HTTPS using SharpGIS;
WebClient webClient = new SharpGIS.GZipWebClient();
webClient.Headers["Accept-Encoding"] = "gzip";
var uri = new Uri(pUrl, UriKind.Absolute);
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
webClient.UploadStringTaskAsync(uri, jsonAsString);
But it doesn't compresses the string as well(as using OpenWriteSync method).
You write the post data in the OpenWriteCompleted handler, like this:
void webClient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
Stream s = e.Result;
s.Write(jsonAsByteArray, 0, jsonAsByteArray.Length);
s.Flush();
s.Close();
}
You should also add the appropriate error handling.

SOAP Parsing in windows phone 7

I will searching since 10 days but i have not succeed in soap parsing in wp7.
My code is below. I get the The remote server returned an error: NotFound. and System.Net.WebException.
code is below :
private const string AuthServiceUri = "http://manarws.org/WS/manarService.asmx";
private const string AuthEnvelope =
#"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<fnGetNewsResponse xmlns=""http://tempuri.org/"">
<fnGetNewsResult></fnGetNewsResult>
</fnGetNewsResponse>
</soap:Body>
</soap:Envelope>";
public void Authenticate()
{
HttpWebRequest spAuthReq = HttpWebRequest.Create(AuthServiceUri) as HttpWebRequest;
spAuthReq.Headers["SOAPAction"] = "http://tempuri.org/fnGetNews";
spAuthReq.ContentType = "text/xml; charset=utf-8";
spAuthReq.Method = "POST";
spAuthReq.BeginGetRequestStream(new AsyncCallback(spAuthReqCallBack), spAuthReq);
}
private void spAuthReqCallBack(IAsyncResult asyncResult)
{
UTF8Encoding encoding = new UTF8Encoding();
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
System.Diagnostics.Debug.WriteLine("REquest is :" + request.Headers);
Stream _body = request.EndGetRequestStream(asyncResult);
string envelope = string.Format(AuthEnvelope,"","");
System.Diagnostics.Debug.WriteLine("Envelope is :" + envelope);
byte[] formBytes = encoding.GetBytes(envelope);
_body.Write(formBytes, 0, formBytes.Length);
_body.Close();
request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
}
private void ResponseCallback(IAsyncResult asyncResult)
{
System.Diagnostics.Debug.WriteLine("Async Result is :" + asyncResult);
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
System.Diagnostics.Debug.WriteLine("Response is :::::::::::::::::::----" + request.EndGetResponse(asyncResult));
if (request != null && response != null)
{
if (response.StatusCode == HttpStatusCode.OK)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
}
}
}
I get the error in HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); line...
So, Please help me.
Thanks.
Maybe I am missing something but why not just adding a service reference ?
The service located at 'http://manarws.org/WS/manarService.asmx' is a classic web service and you can browse wsdl. You can add a reference in Visual Studio. It will generate a proxy class to call this webservice. Manual soap parsing is quite painful.
EDIT :
1) Right clic on service reference in your project.
2) Enter your service url. Then click Go.
3) You will have new classes in your project.
Just use them as you want. Exemple :
public void GetBranches()
{
ManarServiceReference.manarServiceSoapClient client = new ManarServiceReference.manarServiceSoapClient();
client.fnGetBranchesCompleted += new EventHandler<ManarServiceReference.fnGetBranchesCompletedEventArgs>(client_fnGetBranchesCompleted);
client.fnGetBranchesAsync();
}
void client_fnGetBranchesCompleted(object sender, ManarServiceReference.fnGetBranchesCompletedEventArgs e)
{
//TODO
}
Follow these steps to know how to use a SOAP service
-- Create a new project.
-- Right-click on the Project name and click on "Add Service Reference"...
Then provide address as "http://manarws.org/WS/manarService.asmx?wsdl" and click Go.
-- Once service information is downloaded, provide Namespace something like
"MyMemberService" at the bottom and click Ok.
Now that your proxy classes should be ready.
Go to your Mainpage.xaml.cs and type 'client' there..you should probably get a class with the name "ManarServiceClient".
If you get that, then try to call the suitable methods of that class.
For an example,
ManarServiceClient client = new ManarServiceClient();
client.fnGetNewsResponseCompleted += new EventHandler<fnGetNewsResponseCompletedEventArgs>(client_fnGetNewsResponseCompleted);
client.fnGetNewsResponseAsync();
Note: I am not with my working system, so cannot give you exact code. All the above is a guessed code and shall point you in the right direction. Will test my code and update soon.
If you create of an asmx web service. The first call is incredibly slow.

How to call a PHP file using Windows Phone application?

I want to create a simple login functionality in WP7 app using remote MySQL database using PHP as back-end. I have never used this in C#, so I don't know how to do this.
You can use WebClient or HttpWebRequest class to make a web request and get the response.
Here is a sample code on how to make a request and get response
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://someurl", UriKind.Absolute));
And the asynchronous response handler is here
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var response= e.Result; // Response obtained from the web service
}
The above example works for any web service(it may be PHP or jsp or asp etc).
All that you need to do is to make a proper request and handling the response

HttpWebRequest and WebClient returning NotFound on Windows Phone 7 but not i normal console application

I'm trying to download a regular JSON string from this url https://valueboxtest.lb.dk/mobile/categories from a Windows Phone 7 Application.
I have tried to both use WebClient and HttpWebRequest. They both throw an exception
“The remote server returned an error: NotFound”
This is the code for using the WebClient
var webClient = new WebClient();
webClient.DownloadStringCompleted += (client_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri("https://valueboxtest.lb.dk/mobile/categories"));
The eventhandler then just show the content, but e.Result throws the above mentioned exception:
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled) MessageBox.Show(e.Result);
}
For the HttpWebRequest my code looks as follows:
var httpReq = (HttpWebRequest)WebRequest.Create(new Uri("https://valueboxtest.lb.dk/mobile/categories"));
httpReq.BeginGetResponse(HTTPWebRequestCallBack, httpReq);
With the following callback:
private void HTTPWebRequestCallBack(IAsyncResult result)
{
var httpRequest = (HttpWebRequest)result.AsyncState;
var response = httpRequest.EndGetResponse(result);
var stream = response.GetResponseStream();
var reader = new StreamReader(stream);
this.Dispatcher.BeginInvoke(
new delegateUpdate(update),
new Object[] { reader.ReadToEnd() }
);
}
And with the delegate method
delegate void delegateUpdate(string content);
private void update(string content)
{
MessageBox.Show(content);
}
Running it in a console application
Everything works just fine and the JSON string is returned with no problems and I am able to print the result to the console.
Different URL does work on WP7
The weird thing is that the URL http://mobiforge.com/rssfeed actually works fine in both of the above mentioned scenarios.
This issue occurs both in the Emulator and on an actual device.
What could be wrong? Is the REST service returning the data in misbehaving way? I really hope you can help me!
Note: I'm not running Fiddler2 at the same time!
The reason is because that site does not have a valid certificate. Just try it on Mobile Internet Explorer and you'll get the prompt about an issue with the certificate.
How to ignore SSL certificates
Mobile devices are stricter when it comes to SSL certificates.
If you want to get this app into a production environment, you'll either need to write a wrapper for this server (if it's not your own), or get a valid certificate. In the short-term, for testing, you can add a certificate into your device.
Here's a tool which might help you install a certificate.

Accessing a website using C#

I'm trying to make an App for windows phone 7. This app will basiclly retrive information from a website that we use at work as our working schedule then rearrange the retrived info into a metro style UI. To be honest i don't know where to start ie. how to retrive the info. Should i use webclient class? httpwebrequest class? or something else?
All idea are appriciated
Here is a:-
Update:-
Okay either im totally stupid or there is something wrong with the code i'm writing, that i can't figure it out. I was using the same code that you wrote BUT i still get an error that a definition for Proxy is not in the System.Net.WebRequest :( This is my code (the working version):-
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
string url = "https://medinet.se/*****/schema/ibsef";
WebRequest request = WebRequest.Create(url);
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallBack), request);
}
private void ReadWebRequestCallBack(IAsyncResult callbackResult)
{
try
{
WebRequest myRequest = (WebRequest)callbackResult.AsyncState;
WebResponse myResponse = (WebResponse)myRequest.EndGetResponse(callbackResult);
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
string results = httpwebStreamReader.ReadToEnd();
Dispatcher.BeginInvoke(() => parsertextBlock.Text = results);
}
myResponse.Close();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
Dispatcher.BeginInvoke(() => parsertextBlock.Text = ex.ToString());
}
}
But if i add request.Proxy=null!! i get an error, that there is no definition for Proxy in (System.Net.WebRequest). And to be honest i start getting mad of this.
Yours
/Omar
The process is called ScreenScrape and i recommend you to use Html Agility Pack http://htmlagilitypack.codeplex.com/ . Make a web service that retrieves the information from your website and rearranges to appropriate format. Use your web service by a phone and display your data.
Use WebRequest ( http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) and WebResponse ( http://msdn.microsoft.com/en-us/library/system.net.webresponse(v=vs.100).aspx) .
TIP: Set the WebRequest.Proxy property ( http://msdn.microsoft.com/en-us/library/system.net.webrequest.proxy.aspx) to null, as i find it will be much faster.
UPDATE: More info on WebRequest Proxy property
Set Proxy = null on the WebRequest object to avoid an initial delay (that way the request won't start auto detecting proxies, which i find it's faster).
WebRequest req = WebRequest.Create("yourURL");
req.Proxy = null;
It's in the System.Net namespace so put an using statement using System.Net; or
System.Net.WebRequest req = WebRequest.Create("yourURL");
req.Proxy = null;
Regards.

Resources