How to Create http Web Request in Windows Phone Silverlight Project? - c#

I want to make an Http Post and get response from Windows Phone App...Here is how I would have done it in ASP.net.
string strUrl = "http://.....";
WebRequest request = HttpWebRequest.Create(strUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = (Stream)response.GetResponseStream();
StreamReader readStream = new StreamReader( s );
string dataString = readStream.ReadToEnd();
response.Close();
s.Close();
readStream.Close();
But I cannot do this as it gives an error that GetResponse method cannot be Used in Silverlight Project. What is an alternative to this and how do I do it?

Most methods that cause blocking behaviour have been eliminated from the WP/Silverlight APIs (the idea here is not to give the developer any opportunity to inadvertently lock up the UI).
Synchronous IO falls into this category.
You need to rewrite your method using async methods:
public async Task<SomeReturnType> MyMethod()
{
//...
HttpWebResponse response =
(HttpWebResponse)(await request.GetResponseAsync());
//...
}

Related

How to Post a web request and receive a file from web API response?

I have an Infopath Form Template on Sharepoint, I want to add a button there so when the user clicks on it, it will POST an string to the following Web API. The following web API is tested and returns an excel file as shown:
I want to Post the FileName of the excel file using post request and it is important for me the request method to be POST type. and then the user will download a file with the specified 'FileName'.
Actually i want to use post method because at the next stage i will send the content of the excel file too.
Important Note: I only can use .Net FrameWork 3.5 because this is the only framework supported in InfoPath Form Templates.
[HttpPost]
public HttpResponseMessage Post([FromBody]string FileName)
{
string reqBook = "c:\somefile.xlsx";
//converting Excel(xlsx) file into bytes array
var dataBytes = File.ReadAllBytes(reqBook);
//adding bytes to memory stream
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = FileName;
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return httpResponseMessage;
}
When you perform the HttpPost on the client side, you will want to read the HttpResponseStream to get the byte data of the response stream.
Once you have the response stream data, you can then deserialize it to the type of object in C# you want, or you could alternatively just write it to the disk as
File.WriteAllBytes("someexcel.xlsx",data);
An easy way to do it would be with the HttpClient class.
HttpClient client = new HttpClient();
var response = client.PostAsync("", null).Result;
var content = response.Content.ReadAsByteArrayAsync().Result;
File.WriteAllBytes("excel.xlsx", content);
Just fill in the PostAsync bit with the Url and the content you wish to post.
I am using .Result to keep everything synchronous - but you can use 'await' if you prefer.
If you are working with HttpWebRequests - then the process becomes more complicated, as you need to manage the streams yourself.
The HttpClient will manage and handle it all for you - so I recommend it, unless there is something special it needs to do that it currently does not.
Due to your .Net 3.5 requirement:
private static HttpWebResponse MakeRequest(string url, string postArgument)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/form-data;";
Stream stream = request.GetRequestStream();
string result = string.Format("arg1={0}", postArgument);
byte[] value = Encoding.UTF8.GetBytes(result);
stream.Write(value, 0, value.Length);
stream.Close();
return (HttpWebResponse)request.GetResponse();
}
You can then do:
var response = MakeRequest("http://mywebsite.com/ProcessExcel", "accounts.xlsx");
And then do
Stream objStream = response .GetResponseStream();
BinaryReader breader = new BinaryReader(objStream);
byte[] data= breader.ReadBytes((int)webresponse.ContentLength);
File.WriteAllBytes("excel.xlsx",data);

GDax API GET request always returns Error 400

I'm trying to get the order book from GDAX (link to documentation of the call) but when doing it from the c# executable I always get Error 400 - Bad request.
When taking the actual URL and pasting it into my browser, it works fine.
String URL = "https://api.gdax.com/products/BTC-USD/book?level=2";
WebRequest request = WebRequest.Create(URL);
WebResponse response = request.GetResponse();
The actual issue with your API call is , the API is expecting a user-agent string while making the request: Below is the code in working condition:
try
{
String URL = "http://api.gdax.com/products/BTC-USD/book?level=2";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.UserAgent = ".NET Framework Test Client";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
}
}
catch(WebException ex)
{
HttpWebResponse xyz = ex.Response as HttpWebResponse;
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(xyz.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
}
}
Basically ProtocolError indicates that you have received the response but there is an error related to protocol, which you can observe, when you read the response content from exception. I have added catch to handle the exception and read ex.Response (which is HttpWebResponse) and could see that the API is asking for user-agent to be suppllied while making the call. I got to see the error as "{"message":"User-Agent header is required."}"
You can ignore the code inside the exception block, I used it only to see what is the actual response message, which contains actual error details
Note: I have boxed WebRequest to HttpWebRequest to have additional http protocol related properties and most importantly "UserAgent" property which is not available with the WebRequest class.
You need to Accept the certificarte, Google for access to a https webrequest.
Like this

WindowsPhone HttpWebRequest to ashx WebService

I have a problem with HttpWebRequest:
I have an ashx code in a visual studio ws that simply does:
public void ProcessRequest(HttpContext context)
{
var a = context.Request.Form["a"];
var b = context.Request.Form["b"];
context.Response.Write(a + " " + b);
}
I tried to call it with advancedRestClient and it worked, but if i call it with my windows phone device I get a not found exception and the request doesn't reach any breakpoint.
this is my WP code:
public void PostIt2()
{
string url = "http://localhost/blablacode/ecc.ashx";
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
// Keep the main thread from continuing while the asynchronous
// operation completes. A real world application
// could do something useful such as updating its user interface.
allDone.WaitOne();
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
string postData = "{'a': 'avar','b':'bvar'}";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
allDone.Set();
}
I took the code from MSDN so i don't know what i'm doing wrong, i also tried a lot of methods found on the internet, the only thing important for me is that i have to use HttpWebRequest and not HttpClient.
Can someone help me please?
Its possible that the problem is not in the code.
Are your services accesible from the phone??
Are your proyect configure with internet access??
If all its ok, look at this post:
httpclient postasync windows phone 8.1 universal app second call 404 error
Ok, really thanks god is friday.
i was using as url "localhost/eccecc.ashx"
device's localhost is not same localhost of computer.

Login to mediawiki by api on wp7

I am trying to create an app for wp7 to login to wikipedia and help with translating the pages.
I am stuck right at the beginning since I can't get it to login through the mediawiki API.
The relevant part of the code goes like this:
data.Append("action=login&lgname" + HttpUtility.UrlEncode(textBox1.Text));
data.Append("&lgpassword=" + HttpUtility.UrlEncode(passwordBox1.Password));
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),request);
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
postStream.Write(byteData, 0, data.Length);
postStream.Close();
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
response.Close();
}
The problems are:
On the GetRequestStreamCallback I can't pass the data string from the main function. How do I do this?
On the GetResponseCallback function how do I return the responsestring String so that I can output later?
What you're actually trying to do is two asynchronous operations, one after another - it's worth remembering that the BeginXxx methods return before they've finished - so in your case, you ask for the request stream to write to, and immediately ask for the response, so bad things will ensue.
It's possibly worth looking at other examples, such as those in opensource code - you'll see that you don't typically call BeginGetResponse until you've finished writing to the stream returned by EndGetRequestStream

Get the source of some website from asp.net code

Is there any way that I could get the source of a website (as a string preferably), let's say www.google.com, from some c# code inside code behind of asp.net website?
edit: of course i mean html code - in every browser you can view it using "view source" in context menu.
Assuming you want to retrieve the html:
class Program
{
static void Main(string[] args)
{
using (WebClient client = new WebClient())
using (Stream stream = client.OpenRead("http://www.google.com"))
using (StreamReader reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
For C#, I prefer to use HttpWebRequest over WebClient because you can have more option in the future like having GET/POST parameter, using Cookies, etc.
You can have a shortest explication at MSDN.
Here is the example from MSDN:
// Create a new HttpWebRequest object.
HttpWebRequest request=(HttpWebRequest) WebRequest.Create("http://www.contoso.com/example.aspx");
// Set the ContentType property.
request.ContentType="application/x-www-form-urlencoded";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
// Start the asynchronous operation.
request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);
// Keep the main thread from continuing while the asynchronous
// operation completes. A real world application
// could do something useful such as updating its user interface.
allDone.WaitOne();
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream object.
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse.
response.Close();
it's not the most obvious (and the best) way but i found out that in windows forms you can use WebBrowser control (if you actually need it), fill it's Url property with the url you need and when it's loaded, read the DocumentText property - it contains the html code of the viewed site.

Categories

Resources