Link is not opening in Windows Phone 8.1 - windows-phone-8.1

I have such code, that work on my Console Project in VS2012 for Desktop, but not work in VS2013 for WP8.
url = "http://lenta.ru/photo/2014/06/23/blackwidow/"
WebRequest request = WebRequest.Create(url);
WebResponse response = await request.GetResponseAsync(); /*from here programm doesn't work on wp8, but works on PC Console Project on VS2012*/
Stream data = response.GetResponseStream();
Why this code work on console project, but not work from my WP8 app?
fix.
Problem is solved by using HttpCLient instead of WebRequest.
HttpClient client = new HttpClient();
try
{
var result = await client.GetStringAsync(url);
}
catch
{
}
client.Dispose();

Problem is solved by using HttpCLient instead of WebRequest.
HttpClient client = new HttpClient();
try
{
var result = await client.GetStringAsync(url);
}
catch
{
}
client.Dispose();

Related

Http Get Request in windows phone 8.1

Iam new to windows phone 8.1 app developement.i got stuck in getting response from API using httpclient get request..can anybody tell the best way to perform the get request from server in windows phone 8.1..thanks in advance
hope the below helps
try{
var client = new HttpClient();
var uri = new Uri("your URI");
//Call. Get response by Async
var Response = await client.GetAsync(uri);
//Result & Code
var statusCode = Response.StatusCode;
//If Response is not Http 200
//then EnsureSuccessStatusCode will throw an exception
Response.EnsureSuccessStatusCode();
//Read the content of the response.
//In here expected response is a string.
//Accroding to Response you can change the Reading method.
//like ReadAsStreamAsync etc..
var ResponseText = await Response.Content.ReadAsStringAsync();
}
catch(Exception ex)
{
//...
}

Upload image to server from windows phone 8.1 using windows.web.http

Iam currently working with windows phone 8.1 application.Iam really new to this
i want to know how to upload an image to webservice from windows phone 8.1 by using windows.web.http.Please help me i want the full details step by step.Thanks in advance
You can do it this way:
Uri resourceAddress = new Uri("http://www.someurl.com/~?lalala");
StorageFile img = await ApplicationData.Current.LocalFolder.GetFileAsync("ImageName.jpg");
Stream inputStream = await img.OpenStreamForReadAsync();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, resourceAddress);
HttpMultipartContent cont = new HttpMultipartContent();
cont.Add(new HttpStreamContent(inputStream.AsInputStream()));
cont.Headers.ContentType = new HttpMediaTypeHeaderValue("image/jpeg");
request.Content = cont;
request.Headers.Connection.Add(new HttpConnectionOptionHeaderValue("Keep-Alive"));
request.Content.Headers.ContentLength = (ulong)inputStream.Length;
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if (response.StatusCode == HttpStatusCode.Ok)
{
return true;
}
or you can replace last "if" with:
using (Stream responseStream = (await response.Content.ReadAsInputStreamAsync()).AsStreamForRead())
{
StreamReader reader = new StreamReader(responseStream);
string result = await reader.ReadToEndAsync();
}
Here is good link with official samples on github: HttpClient sample

Sending a photo to server using httpclient class windows phone 8

i'm trying to send a photo to a server using httpclient class but every time i try i get a 0 byte file , here's my code for sending the image
if (e.ChosenPhoto != null)
{
var fileUploadUrl = Globals.baseUrl + "/laravelProjects/VisWall/public/test2";
var client = new HttpClient();
photoStream.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(e.ChosenPhoto), "image", fileName);
HttpResponseMessage result = new HttpResponseMessage();
await client.PostAsync(fileUploadUrl, content).ContinueWith((postTask) =>
{
try
{
result = postTask.Result.EnsureSuccessStatusCode();
}
catch (Exception exc)
{
MessageBox.Show("errorrrrrr");
}
});
}
i've also checked the length of e.ChoosenPhoto and it's not 0
try this piece of code by using MultipartFormDataContent:
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(token), "token");
var imageForm = new ByteArrayContent(imagen, 0, imagen.Count());
imagenForm.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
form.Add(imagenForm, "image", "nameholder.jpg");
HttpResponseMessage response = await httpClient.PostAsync("your_url_here", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string result = response.Content.ReadAsStringAsync().Result;
You could refer these too:
Uploading image and data as multi part content - windows phone 8
How to upload file to server with HTTP POST multipart/form-data
There are plenty of samples out there, which I've not mentioned here. It would be great if you could give a search before you post here.

HttpClient dosen't get data after update WP8

I have this code to get JSON data from an API for WP8:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(mainURL.ToString());
HttpResponseMessage response = await client.GetAsync("");
string res = await response.Content.ReadAsStringAsync();
var root = await JsonConvert.DeserializeObjectAsync<Rootobject>(res);
Everything works perfectly, but when I update data on the web API from the web site and try to retrieve data again using this code it gets the old data even though accessing the URL in a browser it gets the new data.
When I debug line by line, I see that the "response" object contains the old data.
The only way I have found to fix this is to rebuild the project in this way it works.
How can I properly get the updated data?
There may be some caching involved. Tried adding some random string to the URL, like
client.BaseAddress = new Uri(mainURL.ToString()+"&random="+DateTime.Now.Ticks);
I have same kind of problem. I tried this this may be help you.
HttpWebRequest request = HttpWebRequest.CreateHttp(mainURL.ToString());
request.Method = "GET or Post";
request.BeginGetResponse(ResponseCallBack, request);
void ResponseCallBack(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string jsonString = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Rootobject));
Rootobject yourdata= dataContractJsonSerializer.ReadObject(memoryStream) as Rootobject;
}
}
}

Windows.Web.Http.HttpClient Timeout Option

Due to SSL certificate issue we are using "Windows.Web.Http.HttpClient" API in my app service layer.
I referred below sample for my project.
http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664
How can we implement the timeout option in "Windows.Web.Http.HttpClient" API
You can use a CancellationTokenSource with a timeout.
HttpClient client = new HttpClient();
var cancellationTokenSource = new CancellationTokenSource(2000); //timeout
try
{
var response = await client.GetAsync("https://test.example.com", cancellationTokenSource.Token);
}
catch (TaskCanceledException ex)
{
}
Edit :
With Windows.Web.Http.HttpClient you should use the AsTask() extension method :
HttpClient client = new HttpClient();
System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource(2000);
try
{
client.GetAsync(new Uri("http://example.com")).AsTask(source.Token);
}
catch(TaskCanceledException ex)
{
}