Cannot access a webservice via WP8 emulator - windows-phone-7

I'm developing a windows phone 8 application which access another webservice. On the response code like:
private void OnGetResponse<TRequest, TResponse>(IAsyncResult result)
{
var state = (AsyncRequestState<TRequest, TResponse>)result.AsyncState;
try
{
using (var webResponse = state.WebRequest.EndGetResponse(result))
{
using (var responseStream = webResponse.GetResponseStream())
{
var response = formatter.Deserialize<TResponse>(responseStream);
state.TaskCompletionSource.SetResult(response);
state.Complete();
}
}
}
catch (System.Exception ex)
{
}
}
}
when code executes this line
using (var webResponse = state.WebRequest.EndGetResponse(result))
error throws out saying:
System.Net.WebException: The remote server returned an error: NotFound
But I can access the webservice via the built in IE. This means that the enumelator can access the internet.
So what's the problem ? help please ~

Related

WebApi: Reading errors

I've got a simple web api which is consumed from a mvc project, I keep on getting the 'Response status code does not indicate success' and was wondering how would I get the response body from the error, I can see the error within a rest viewer but can't navigate through to the error. This is the following code within the MVC app
public ActionResult Index()
{
try
{
var uri = "http://localhost:57089/api/values";
using (var client = new HttpClient())
{
Task<string> response = client.GetStringAsync(uri);
object result = JsonConvert.DeserializeObject(response.Result);
return (ActionResult) result;
}
}
catch (Exception ex)
{
return Content(ex.ToString());
}
return View();
}
Within the API controller I'm sending a bad request, here's the code
public IHttpActionResult Get()
{
return BadRequest("this is a very bad request " + System.DateTime.Now.ToUniversalTime());
}
I've tried to use WebException, HttpRequestException as exceptions to catch the error with no luck.
I can see the response body within the rest viewer
I want to be able to navigate to the Error Message so I can pass that to the client (which later will be changed to a guid).
[EDITED]
I've got a solution without using GetStringAsync, but wanted to use that if possible.
Here's the solution
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
HttpResponseMessage responseMessage = httpClient.GetAsync("").Result;
if (responseMessage.IsSuccessStatusCode) return Content(responseMessage.ToString());
var a = responseMessage.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<HttpError>(a);
object value = "";
return Content(result.TryGetValue("ErrorMessage", out value) ? value.ToString() : responseMessage.ToString());
Is there a better way?
Using WebException you should be able to get to the ResponseStream and the custom error message like this:
catch (WebException e)
{
var message = e.Message;
using (var reader = new StreamReader(e.Response.GetResponseStream()))
{
var content = reader.ReadToEnd();
}
}
Hope that helps.

Connect to Server using xamarin forms

I'm developing Xamarin Cross platform application. I'm trying to connect to server (http://test.net/login/clientlogin), I need to send these fields (password = "xyz"; platform = iphone; (useremail) = "test#test.com";) along with the request. So that server will check these parameters and returns XML. But we don't know how to add these fields to the request.
When i open the above string url (http://*****/login/clientlogin) i am getting login screen, with in that we have username, password and platform text fields.
Thanks in advance!!!..
This should get you started presuming you are adding the values as headers in the request:
public class TestClient
{
HttpClient client;
public TestClient(){
this.client = new HttpClient ();
}
public void AddHeadersAndGet(){
client.DefaultRequestHeaders.Add ("username", "whatevertheusernameis");
this.GetAsync<WhateverObjectTypeYouAreReceiving> ("theurloftheservice");
}
public async Task<T> GetAsync<T>(string address){
HttpResponseMessage response = null;
response = await client.GetAsync (address);
if (response.IsSuccessStatusCode) {
try {
var responseString = await response.Content.ReadAsStringAsync ();
return new T (Serializer.DeserializeObject<T> (responseString),
response.StatusCode);
} catch (Exception ex) {
}
} else {
}
}
}
The key line for you is:
client.DefaultRequestHeaders.Add ("username", "whatevertheusernameis");

How to set Timeout for httpwebrequest in windows phone 8 app?

i am developing an windows phone 8 app , in my app i am calling services and downloading some data into my app .
i am using httpwebrequest for request, but i am not able to set timeout to my httpwebrequest object.
This is how i have created and used my httpwebrequest :-
public async Task<string> ServiceRequest(string serviceurl, string request, string methodname)
{
string response = "";
try
{
var httpwebrequest = WebRequest.Create(new Uri(serviceurl)) as HttpWebRequest;
httpwebrequest.Method = "POST";
httpwebrequest.Headers["SOAPAction"] = "http://tempuri.org/" + iTestservice + "/" + methodname + "";
httpwebrequest.ContentType = "text/xml";
byte[] data = Encoding.UTF8.GetBytes(request);
using (var requestStream = await Task<Stream>.Factory.FromAsync(httpwebrequest.BeginGetRequestStream, httpwebrequest.EndGetRequestStream, null))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
response = await httpRequest(httpwebrequest);
}
catch (Exception ex)
{
return null;
}
return response;
}
public async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
received = await sr.ReadToEndAsync();
}
}
}
return received;
}
My Doubt is :-
1) How can i set timeout property to Httpwebrequest ??
2)What are the different ways in which i can set the timeout property in my windows phone 8 app ??
Please let me know .
Thanks in Advance.
You can't use HttpWebRequest.Timeout on Windows Phone because it doesn't exist for that platform.
If you're open to using a beta library, you could install HttpClient via NuGet and use its Timeout property.
Otherwise, you're probably best off to use TaskEx.Delay, which is part of Microsoft.Bcl.Async. After installing that library, you would replace this line:
response = await httpRequest(httpwebrequest);
with this:
var httpTask = httpRequest(httpwebrequest);
var completeTask = await TaskEx.WhenAny(httpTask, TaskEx.Delay(5000));
if (completeTask == httpTask)
return await httpTask;
else
return null; // timeout
You can use HttpStatusCode.HttpStatusCode is an enum which can be used to get the type of error in HttpWebRequest.
catch(WebException ex)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
if(response.StatusCode==HttpStatusCode.GatewayTimeout)
{
}
}
The GatewayTimeout indicates that an intermediate proxy server timed out while waiting for a response from another proxy or the origin server.For more information you can refer to the msdn
site for this.Hope it helps

Windows Phone POST method WebClient class

I am new to this forum as well as Windows Phone Development. I am currently developing an app in which I am working with a Web-Service and I need to make a POST request to a web service.
I am trying to accomplish a user login functionality here for which,
-> http://abc.com/login (URI)
-> (PARAMETERS)
apikey: 32 byte long alpha-numeric
username: 3-15 characters
password: 3-15 characters
So for this I am trying to use WebClient class' UploadStringSync method in order to POST the data. My code is as follows.
WebClient wc1 = new WebClient();
wc1.UploadStringAsync(new Uri("http://abc.com/login"),"POST","?apikey=" + Apikey + "&username=username&password=password");
wc1.UploadStringCompleted += new UploadStringCompletedEventHandler(wc1_UploadStringCompleted);
void wc1_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
Execution stops here at MessageBox line and throws message saying 'The remote server returned an error: NotFound.'
Is there any problem with the way I am passing the parameters? I tried to search for the working implementation everywhere but was unable to find it.
Can anybody help me with this? This is a starting point of my project and really need help on this one. Any help would be much appreciated.
try this:
public void Post(string address, string parameters, Action<string> onResponseGot)
{
Uri uri = new Uri(address);
HttpWebRequest r = (HttpWebRequest)WebRequest.Create(uri);
r.Method = "POST";
r.BeginGetRequestStream(delegate(IAsyncResult req)
{
var outStream = r.EndGetRequestStream(req);
using (StreamWriter w = new StreamWriter(outStream))
w.Write(parameters);
r.BeginGetResponse(delegate(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)r.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
onResponseGot(reader.ReadToEnd());
}
}
}
catch
{
onResponseGot(null);
}
}, null);
}, null);
}
I did this and it worked
WebClient web = new WebClient();
web.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
web.UploadStringAsync((new Uri("http://www.something.com/?page=something")), "POST", string.Format("v1=onevalue&v2=anothervalue"));
web.UploadStringCompleted += web_UploadStringCompleted;
and after upload is complete to get the html i used htmlagilitypack, you can just get the whole html using e.Result
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(e.Result);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//body//table");
MessageBox.Show(node.InnerText);

httpwebrequest BeginGetResponse callback fires in 60 Seconds WP7

I am trying to fetch some data to WP7 device using a websevice.
I am using HttpWebRequest object to get the data from my service... everything works well on WP7 Emulator, but when i try to run the application on WP7 device BeginGetResponse callback fires after 1 min/60 seconds with response status "Not Found".
But if service returns data before 60 seconds then it works on WP7 device as well....
i have crated a sample web service with a sample method which has Thread.Sleep for two minutes it works on WP7 Emulator but not working on WP7 device....
did anybody faces any issue like this before???
Please help me out.
Thanks,
SK
I am using below code to hit the service... same code is working on WP7 Emulator but on WP7 device...
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = method;
request.Headers["SOAPAction"] = #"http://tempuri.org/HelloWorldT";
request.Headers["KeepAlive"] = "true";
var res = request.BeginGetRequestStream(
new AsyncCallback((streamResult) =>
{
soapRequestEnvelope = #"<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HelloWorldT xmlns='http://tempuri.org/' xmlns:a='http://schemas.datacontract.org/2004/07/WindowsFormsApplication1.ServiceReference1' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'/></s:Body></s:Envelope>";
byte[] requestBytes = Encoding.UTF8.GetBytes(soapRequestEnvelope);
try
{
using (Stream requestStream = request.EndGetRequestStream(streamResult))
{
requestStream.Write(requestBytes, 0, Encoding.UTF8.GetByteCount(soapRequestEnvelope));
}
}
catch (Exception e)
{
}
request.BeginGetResponse(new AsyncCallback((ar) =>
{
try
{
HttpWebRequest Request = (HttpWebRequest)ar.AsyncState;
if (Request != null)
{
using (HttpWebResponse webResponse = (HttpWebResponse)Request.EndGetResponse(ar))
{
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
string text = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
}
}), request);
}), request);

Resources