How to send POST request with parameters asynchronously in windows phone 8 - windows-phone-8

I would like to send POST request in windows phone 8 environment my code is running successfully but i am getting NotFound exception. Its mean is i want to POST some data but i am sending null. So please let me know how to send POST Request asynchronously with Data in windows phone 8 environmet. I tried following links but not helpful.
link link2
I approached like this
private async Task<LastRead> SyncLastReadPOST(LastRead lastreads, bool actionStatus)
{
string jsondata = "";
actionStatus = false;
apiData = new LastReadAPI()//It is global variable from apiData this object has the information
{
AccessToken = thisApp.currentUser.AccessToken,
Book = lastreads.Book,
Page = lastreads.Page,
Device = lastreads.Device
};
jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(apiData);
LastRead responsedData = new LastRead();
Uri lastread_url = new Uri(string.Format("{0}lastread", url_rootPath));
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(lastread_url);
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json;odata=verbose";
webRequest.Method = "POST";
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
catch { }
return responsedData;
}
private void GetRequestStreamCallback(IAsyncResult ar)
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
Stream postStream = request.EndGetRequestStream(ar);
var input = Newtonsoft.Json.JsonConvert.SerializeObject(jsondata);//jsondata is my global data variable in json format.
byte[] byteArray = Encoding.UTF8.GetBytes(input);
postStream.WriteAsync(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallback), request);
}
private void GetResponseStreamCallback(IAsyncResult ar)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
HttpWebResponse response;
//In following line i am getting the exception notFound.
response = (HttpWebResponse)webRequest.EndGetResponse(ar);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReaders = new StreamReader(streamResponse);
var responces = streamReaders.ReadToEnd();
streamResponse.Close();
streamReaders.Close();
response.Close();
}
catch(Exception ex)
{
}
}
As far as i know notFound exceptions comes when we are not posting any data while using the POST request method. you can see i have mentioned the data i am passing into the GEtRequestStreamCallback. I have mentioned a note. Please help me. Where i am going to wrong.

Try setting the content-type to application/json; charset=utf-8
Also, you can do all that stuff in nicer and shorter way(sample):
var wc = new WebClient();
//SET AUTH HEADER IF NECESSARY
//wc.Headers["Authorization"] = "OAUTH "+TOKEN;
wc.Headers["Content-Type"] = "application/json;charset=utf-8";
wc.UploadStringCompleted += (s, er) =>
{
if (er.Error != null) MessageBox.Show("Error\n" + er.Error);
else MessageBox.Show(er.Result);
};
string data = JsonConvert.SerializeObject(MY_DATA_OBJECT);
MessageBox.Show(data);
wc.UploadStringAsync(new Uri(POST_URI), "POST", data);

I did it with the help of HttpClient inplace of WebClient. Following few lines will do magic. :)
HttpClient hc = new HttpClient();
hc.BaseAddress = new Uri(annotation_url.ToString());
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, myUrl);
HttpContent myContent = req.Content = new StringContent(myJsonString, Encoding.UTF8, "application/json");
var response = await hc.PostAsync(myUrl, myContent);
//Line for pull out the value of content key value which has the actual resposne.
string resutlContetnt = response.Content.ReadAsStringAsync().Result;
DataContractJsonSerializer deserializer_Json = new DataContractJsonSerializer(typeof(MyWrapperClass));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resutlContetnt.ToString()));
AnnotateResponse = deserializer_Json.ReadObject(ms) as MyWrapperClass;

Related

How to upload image to server (using POST) which return json in Windows Phone 8.1 RT?

I am making an app which can upload image to a server (the server works well), and I use this method to upload my image to it, but when I get the respond from the result, it return a null string, can you explain for me what did I do wrong.
I followed this method: How to upload file to server with HTTP POST multipart/form-data
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
byte[] bytes = await Converter.GetBytesAsync(storageFile);
form.Add(new ByteArrayContent(bytes, 0, bytes.Count()), "\"upload-file\"", "\"test.jpg\"");
HttpResponseMessage response = await httpClient.PostAsync("my-url", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
Debug.WriteLine("res: " + sd); // this return a null string
The request return like this:
--a81d2efe-5f2e-4f84-83b9-261329bee20b
Content-Disposition: form-data; name="upload-file"; filename="test.jpg"; filename*=utf-8''%22test.jpg%22
����Ivg?�aEQ�.�����(��9%�=��>�C�~/�QG$�֨������(�`������QE��Z��
Can you help me please!
P/s: Here is my convert method
public static async Task<byte[]> GetBytesAsync(StorageFile file)
{
byte[] fileBytes = null;
if (file == null) return null;
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
return fileBytes;
}
This might help
private async Task<string> UploadImage(StorageFile file)
{
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("fileToUpload");
form.Add(content, "fileToUpload");
var stream = await file.OpenStreamForReadAsync();
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = file.Name
};
form.Add(content);
var response = await client.PostAsync("my-url", form);
return response.Content.ReadAsStringAsync().Result;
}
Use ByteArrayContent instead of StringContent. That Should work.
And if you are expecting a stream-response you should use ReadAsStreamAsync instaed of ReadAsStringAsync.

How to return HTML from ASP.NET Web API when given url

I want to create a WEB API that will accept a url and return the url's "HTML" page. Please how should I do this? I believe I have the wrong code. HI am so new to this. Thanks*
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
response.Content = new StringContent("https://myurl.com");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
Do you mean do something like this?
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
System.Net.WebRequest req = System.Net.WebRequest.Create("https://myurl.com");
using (System.Net.WebResponse resp = req.GetResponse())
using (System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream()))
response.Content = sr.ReadToEnd().Trim();
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
My extension for AspNetCore:
public static ContentResult GetDashboardAsHtml(this AbpController controller)
{
var request = WebRequest.Create($"{controller.Request.Scheme}://{controller.Request.Host}/hangfire");
using var response = request.GetResponse();
using var streamReader = new System.IO.StreamReader(response.GetResponseStream());
return new ContentResult
{
Content = streamReader.ReadToEnd().Trim(),
ContentType = "text/html"
};
}

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.

Send Cookies with HTTPWebRequestion through WP8 App

I have to send the cookies to server for every subsequent HTTPWebRequest. My code goes below.
class APIManager
{
CookieContainer cookieJar = new CookieContainer();
CookieCollection responseCookies = new CookieCollection();
private 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))
{
cookieJar = request.CookieContainer;
responseCookies = response.Cookies;
received = await sr.ReadToEndAsync();
}
}
}
return received;
}
public async Task<string> Get(string path)
{
var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
request.CookieContainer = cookieJar;
return await httpRequest(request);
}
public async Task<string> Post(string path, string postdata)
{
var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
request.Method = "POST";
request.CookieContainer = cookieJar;
byte[] data = Encoding.UTF8.GetBytes(postdata);
using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
return await httpRequest(request);
}
}
Every time i ask for the question people say that i have to set the cookie container with request by following code line.
request.CookieContainer = cookieJar;
and i used it but still server returns the 'token does not match' error. Do i need to talk to the vendor for it?
Following image shows my problem and requirement.
I haven't seen you do something with the cookieJar !
//Create the cookie container and add a cookie.
request.CookieContainer = new CookieContainer();
// This example shows manually adding a cookie, but you would most
// likely read the cookies from isolated storage.
request.CookieContainer.Add(new Uri("http://api.search.live.net"),
new Cookie("id", "1234"));
cookieJar in your APIManager is a member, everytime your instance APIManager, the cookieJar is a new instance. you need to make sure cookieJar contains what the website needs.
you can have a look at this How to: Get and Set Cookies

HttpWebRequest Post method error in Windows phone 8

HttpWebRequest in Windows phone 8
I am developing a windows phone 8 app using c#/xaml. I am facing some issues with httpwebrequest class. I want to download data from server using post method.But httpwebrequest is not working as expected. It is returning error (The remote server returned an error: NotFound) when i try to call webservices subsequently. What could be the reason?. Please help...Following is my code.
string response = "";
httpwebrequest = WebRequest.Create(new Uri(serviceurl)) as HttpWebRequest;
httpwebrequest.Method = "POST";
httpwebrequest.ContentType = "application/json";
byte[] data = Serialization.SerializeData(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);
var result = Serialization.Deserialize<T>(response);
return result;
}
public async Task<string> httpRequest(HttpWebRequest request)
{
try
{
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();
}
}
response.Close();
}
return received;
}
catch(Exception ex)
{
return "";
}
}
Have you checked the inner exception? Because i had a similar problem an when i checked the inner exception i found that i got another error from the server. Check also the real http status code into the response header.