In my Windows phone app, I want to take a simple string url, and when that url is entered in a browser, it only shows a JSON string on the webpage, as a response.
So I want to enter that url in my app and just get that JSON string in return, How can I do it? I've tried following but getResponse function isn't present in Silverlight.
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();
I would use the HttpClient instead it is much easier to use. You need to add the HttpClient Nuget package to use it in the WP Silverlight project.
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
using (HttpClient client = new HttpClient())
{
string data = await client.GetStringAsync("http://msdn.microsoft.com");
}
}
Related
Before I upgraded to the newest .NetCore I was able to run the HttpWebRequest, add the headers and content Type and pull the stream of the JSON file from Twitch. Since the upgrade this is not working. I receive a Web Exception each time I go to get the response Stream. Nothing has changed with twitch because it still works with the old Bot. The old code is below:
private const string Url = "https://api.twitch.tv/kraken/streams/channelname";
HttpWebRequest request;
try
{
request = (HttpWebRequest)WebRequest.Create(Url);
}
request.Method = "Get";
request.Timeout = 12000;
request.ContentType = "application/vnd.twitchtv.v5+json";
request.Headers.Add("Client-ID", "ID");
try
{
using (var s = request.GetResponse().GetResponseStream())
{
if (s != null)
using (var sr = new StreamReader(s))
{
}
}
}
I have done some research and found that I may need to start using either an HttpClient or HttpRequestMessage. I have tried going about this but when adding headers content type the program halts and exits. after the first line here: (when using HttpsRequestMessage)
request.Content.Headers.ContentType.MediaType = "application/vnd.twitchtv.v5+json";
request.Content.Headers.Add("Client-ID", "rbp1au0xk85ej6wac9b8s1a1amlsi5");
You are trying to add a ContentType header, but what you really want is to add an Accept header (your request is a GET and ContentType is used only on requests which contain a body, e.g. POST or PUT).
In .NET Core you need to use HttpClient, but remember that to correctly use it you need to leverage the use of async and await.
Here it is an example:
using System.Net.Http;
using System.Net.Http.Headers;
private const string Url = "https://api.twitch.tv/kraken/streams/channelname";
public static async Task<string> GetResponseFromTwitch()
{
using(var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.twitchtv.v5+json"));
client.DefaultRequestHeaders.Add("Client-ID", "MyId");
using(var response = await client.GetAsync(Url))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync(); // here we return the json response, you may parse it
}
}
}
I'm using https://timercheck.io/YOURTIMERNAME/60 to create timer, and when the timer end the API Manager to return both an error code and some JSON content
This is the JSON data when timer end:
{"errorMessage":"504: timer timed out"}
When the timer still countdown:
{"timer":"neo308CCEACbid","request_id":"e54f484e-1e64-11e6-9552-3950b2ec2d5c","status":"ok","now":1463732937,"start_time":1463732935,"start_seconds":180,"seconds_elapsed":2,"seconds_remaining":178,"message":"Timer still running"}
Because of the error code, i get error on Visual Studio and App force close on my Android. I only want to get the errorMessage in JSON. I'm using Visual Studio 2015 and Xamarin to make this project.
Thanks in advance
UPDATE:
I'm using this to get web response
private async Task<string> FetchUserAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (var sr = new StreamReader(response.GetResponseStream()))
{
string strContent = sr.ReadToEnd();
return strContent;
}
}
}
And call it like this:
CekTimer dataWaktu = JsonConvert.DeserializeObject<CekTimer>(await FetchUserAsync(url));
I assume you are using HttpClient and GetStringAsync, and that the HttpResponse Status code is a 504 too, like in the Json Content.
The shortcut methods like GetStringAsync all make a call to EnsureSuccessStatusCode, which of cause throws an exception on a 504 (see source here).
You can just make a direct get Request:
var client = new HttpClient();
var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, yourUri));
var json = await response.Content.ReadAsStringAsync();
I found the answer of my problem, because of webservice return error code, just simply use WebException and get the StatusCode like this :
private async Task<string> FetchUserAsync(string url)
{
try
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (var sr = new StreamReader(response.GetResponseStream()))
{
string strContent = sr.ReadToEnd();
return strContent;
}
}
}
catch (WebException e)
{
string a = ((HttpWebResponse)e.Response).StatusCode.ToString();
//Toast.MakeText(this, a, ToastLength.Long).Show();
if (a == "GatewayTimeout")
{
return "{'errorMessage':'504: timer timed out'}";
}
else
{
internetDropDialog();
return "";
}
}
}
I think it isn't the best answer, but it can help you to move on from this problem
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());
//...
}
Can anyone suggest a way to search a string on the web page, using ASP .net C#
Scenario: A textbox have some value(string), and on the click of button it searches that value(string) on some xyz page.
Example: I have "youtube"(string) in the textbox, and when I press submit button. That submit button gets the entire information of say Google.com(rendered page), and searches for "youtube"(string) on that Google.com
Possible solution:
I think that can be achieved by some-how rendering the page temporarily some-where, or some-how storing the response in any string or array, and then look that string.
Can anyone suggest a way to solve the above scenario. If possible with an example.
use a web request to get the page:
WebRequest request = WebRequest.Create(http://www.google.com);
request.Method = "GET";
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
reader.Close();
response.Close();
then just search on your content string:
int i = content.IndexOf("youtube");
or however you want to search for it.
You could do this with async/await if you are using .NET 4.5
static void Main(string[] args)
{
var content = GetUrlContents("http://www.google.com");
if (content.Result.Contains("Google"))
Console.WriteLine("Google found!");
Console.Read();
}
static async Task<string> GetUrlContents(string url)
{
HttpClient client = new HttpClient();
var content = await client.GetStringAsync(url);
return content;
}
Or if you want synchronous, you could do this kind of method
public static string GetUrlContents(string url)
{
return new WebClient().DownloadString(address);
}
I want to get the http request header and also the post data from a given URL.... how to do that?.... I have to display http request header, http response header, content of a given url and post data...
Below is my code for that....
private void button1_Click(object sender, EventArgs e)
{
try
{
string url = txtUrl.Text;
HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse Response = (HttpWebResponse)WebRequestObject.GetResponse();
HttpStatusCode code = Response.StatusCode;
txtStatus.Text = code.ToString();
txtResponse.Text = Response.Headers.ToString();
// Open data stream:
Stream WebStream = Response.GetResponseStream();
// Create reader object:
StreamReader Reader = new StreamReader(WebStream);
// Read the entire stream content:
string PageContent = Reader.ReadToEnd();
// Cleanup
Reader.Close();
WebStream.Close();
Response.Close();
txtContent.Text = PageContent;
// var request = WebRequest.Create("http://www.livescore.com ");
//var response = request.GetResponse();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
But how to get post data and http request header that i dont know...pls help
It's not very clear what you are trying to accomplish with mixed references to GET, POST, and request and response headers.
If you can make the request you want in a browser and use Fiddler to intercept it, you can use the Fiddler add-on Request-To-Code to generate C# code that will perform the request. The generated code would probably be a good place for you to start - from something that works and with which you can further tinker.
Fiddler is a great way to learn more about HTTP.