how to use HttpClient in WindowsPhone 8 - windows-phone-8

Hey everyone i have a big problem with this thing. i'm trying to use HttpClient method in my new project. i try this code:
var httpClient = new HttpClient();
var request = await httpClient.GetAsync(new Uri("http://www.google.com/", UriKind.RelativeOrAbsolute));
var txt = request.Content.ReadAsStringAsync();
MessageBox.Show(txt.Result);
i think it is true code because i wrote it in Console app and it works fine. Then i opened a new WindowsPhone 8 project and write this code.And code doesn't work, it returns Null. Sometimes it works but generally not. i thought my Visual Studio wasnt work good and i deleted it and re-install it, and nothing had been changed. what do you think?

try this.
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(new Uri("http://www.google.com/", UriKind.RelativeOrAbsolute));
response.EnsureSuccessStatusCode();
var txt = response.Content.ReadAsStringAsync();
MessageBox.Show(txt.Result);
make the breakpoint in the line response.EnsureSuccessStatusCode(); to make sure response httpcode is 200 every time.

You shouldn't be calling Result. Try this instead:
var httpClient = new HttpClient();
var request = await httpClient.GetAsync(new Uri("http://www.google.com/", UriKind.RelativeOrAbsolute));
var txt = await request.Content.ReadAsStringAsync();
MessageBox.Show(txt);

Related

Adobe AIR file upload response data in complete handler is null while fiddler(web debugger) shows that json is returned as response

When uploading a file from adobe AIR to a backbone server, the response returned is not anyway accessible when using file.upload(request) function, while i can see json response in fiddler(web debugger and in task manager), also it was working fine when using URLLoader.load() instead of file.upload()
var url = "api url of backbone server ";
request = null;
file = null;
request = new air.URLRequest(url);
request.useCache = false;
var authorization = new air.URLRequestHeader("Authorization", "Bearer "+accessToken);
var contentType = new air.URLRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
var Accept = new air.URLRequestHeader("Accept", "application/json;charset=UTF-8");
request.requestHeaders.push(authorization);
request.requestHeaders.push(contentType);
request.requestHeaders.push(Accept);
file = new air.File(path);
pathNative = file.nativePath;
var directory = getDirectoryFromPath(pathNative);
params = new air.URLVariables();
params.parent_id = directory.directory_id;
params.name = file.name;
request.data = params;
request.method = air.URLRequestMethod.POST;
request.contentType = 'multipart/form-data, boundary='+boundary;
var file = new air.File(path);
file.upload(request);
file.addEventListener(air.Event.COMPLETE, function(e){
air.Introspector.Console.log(file);
air.Introspector.Console.log(e);
air.Introspector.Console.log(e.target.data);
});
This is the console for complete event as you can see returned data is null.
see console
while in fiddler shows that json is returned.
see fiddler
Seems like it's a known issue on iOS? Are you trying to do this from iOS?
https://forums.adobe.com/thread/1720117?start=0&tstart=0
I ran into the same problem. Instead of using air.Event.COMPLETE, try to use air.DataEvent.UPLOAD_COMPLETE_DATA:
file.addEventListener(air.DataEvent.UPLOAD_COMPLETE_DATA, function(e){
air.Introspector.Console.log(e.data);
});

how to get pdf file to the temp storage file, from Url in windows phone 8.1

var uri = new System.Uri("ms-appx:///Assets/FixesViaMail_17Dec.pdf", UriKind.Absolute);
StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
This code is working very well because i m using my system file path but whenever i am using this code
var uri = new System.Uri("http://www.visa.com/assets/upload/11458/Hotel/Voucher114581423144270.pdf", UriKind.Absolute);
StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
then i am getting error that is.....
Value does not fall within the expected range.
Please Help me
GetFileFromApplicationUriAsync is only used for loading a file from within your application. To read a file from the web you'll need to download it. You can do this with either the HttpClient (for small files) or BackgroundDownloader (for large files) classes.
var uri = new Uri("http://www.visa.com/assets/upload/11458/Hotel/Voucher114581423144270.pdf");
var httpClient = new HttpClient();
// Always catch network exceptions for async methods
try
{
var response = await httpClient.GetAsync(uri);
// save response out
}
catch
{
// Details in ex.Message and ex.HResult.
}
See Connecting to an HTTP server using Windows.Web.Http.HttpClient (XAML) for more details.
var uri = new Uri("http://www.visa.com/assets/upload/11458/Hotel/Voucher114581423144270.pdf");
BackgroundDownloader download = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(uri, destinationFile);
See Transferring data in the background for more details.

How to POST a string and an image in one request using HttpClient?

I have a string and an image I need to POST to a web server using the HttpClient in the Windows Runtime.
How can I post two things in one request using the HttpClient?
Easy! Try this:
using Windows.Web.Http;
using Windows.Web.Http.Headers;
private async void Foo()
{
// the image
var fileStream = await file.OpenReadAsync();
var streamContent = new HttpStreamContent(fileStream);
var filename = "myImage.png";
// the text
var text = "oompa loompas";
var stringContent = new HttpStringContent(text);
// Putting all together.
var formDataContent = new HttpMultipartFormDataContent();
formDataContent.Add(streamContent, "myImage", fileName);
formDataContent.Add(stringContent, "myString");
// Send it to the server.
var response = await (new HttpClient()).PostAsync(uri, formDataContent);
}
For posting a string
HttpClient client = new HttpClient();
HttpContent content = new StringContent(contentstring);
client.PostAsync(url, content);
For posting an image convert Image to stream and stream to string and the then httpcontent.

Send Image File via XHR on Chrome

I'm using HTML5 drag&drop to get images from a user's computer and want to upload them to my Rails server (using Carrierwave on that end). I don't know exactly what I'm doing here, but cobbled together this code from these instructions http://code.google.com/p/html5uploader/wiki/HTML5Uploader
This returns a 500 error - can anyone take a look and help me out with what I'm doing wrong?
var files = e.dataTransfer.files;
if (files.length){
for (var i = 0; i<files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function() {
var bin = reader.result;
var xhr = new XMLHttpRequest();
var boundary = 'xxxxxxxxx';
xhr.open('POST', '/images?up=true&base64=true', true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(window.btoa(bin));
};
};
};
There are a couple of things that could be the culprit. You're reading the file as a binary string, then creating a multipart request, then sending a base64 encoded value.
There's no need to read the file or mess with base64 encoding. Instead, just construct a FormData object, append the file, and send that directly using xhr.send(formData). See my response here.

Sending POST variables via an AIR application

I'm trying to send data via POST, since it's far too long to send via GET.
Here's the code I'm using...
pdfUrl.method = URLRequestMethod.POST;
var vars:URLVariables = new URLVariables();
vars.html = data;
pdfUrl.data = vars;
navigateToURL(pdfUrl);
The problem is that it always sends as GET, and the data in vars.html is too long for my server to receive.
To make matters worse, it seems like AIR can only send GET via navigateToURL.
The issue with this is, I need to open a new browser window and send the POST data so that a script on my server can create a PDF file for the user.
What workarounds are there for this?
I'm not aware of any way to open a new browser window with a POST request, with GET being the default HTTP method used to open pages (which makes sense, really). An alternative, however, would be to POST the data using a simple HTTP request in AIR and once you get a response to the POST request in AIR, you can open a new browser window using a GET request.
So:
POST to your server directly from AIR.
Have your server return some kind of value that you can use in step 3.
Open a new browser window using navigateToURL and attach the value you got from step 2 to the URL.
This should work well, I think.
// Upload MP3-Byte-Array
private function uploadFile():void
{
var uploadURL:URLRequest = new URLRequest();
uploadURL.url = "myfile.php?var1=var1Value&var2=var2Value";
uploadURL.contentType = 'application/octet-stream';
uploadURL.method = URLRequestMethod.POST;
uploadURL.data = heavyDataThatyouWantToPass;
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
urlLoader.load(uploadURL);
}
private function completeHandler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target);
}
myfile.php will be like this:
<?php
$var1 = $_REQUEST['var1Value'] ;
$var2 = $_REQUEST['var2Value'] ;
$heavyData = $GLOBALS[ 'HTTP_RAW_POST_DATA' ];?>