Attempting to get a web request before I attempt to deserilize my url unfortunately none of the conventional methods for making web requests work.
public WeatherModel GetWeather(string url)
{
WeatherModel WeatherData = new JavaScriptSerializer().Deserialize<WeatherModel>(url);
return WeatherData;
}
Does anyone have any suggestions?
You need to send a HTTP request to the URL and parse the response data. You cannot simply deserialize the URL.
Use HttpClient class to send HTTP requests.
https://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.118%29.aspx
Please refer to this link to see how to make HTTP requests using HttpClient.
Related
I can obtain the details of my http request including headers via Fiddler, however I'd like to display the value of my http request and response as part of my MVC web service to ensure the request is valid.
I want to return all of the details of the request as a string so I can return the result to the View for this specific controller.
I am using C# to create the request:
var _httpClientManager = new HttpClientManager(_httpClientPool, _Identity, _errorLogger);
_httpClientManager.HttpRequestHeaders = new Dictionary<string, string>();
_httpClientManager.HttpRequestHeaders.Add("Accept", "application/json");
... extra headers omitted.....
... url and request JSON is omitted
var response = await _httpClientManager.PostAsJsonAsync<IdentityVerificationRequest>(url, request, null);
return View(response);
Basically I'd like to obtain what I am about to Post to the server and include that in the View response.
Its probably a bit of a naïve question, I am quite new working with this.
Is it possible?
Thankyou.
So I am trying to build a program in C#. I want to send a really specific request. Exactly as I receive it in fiddler. Right now I am using fiddlers composer feature to send the request. Here is how I get the request in fiddler
How can I send it exactly as shown on the picture but in a C# console application?
Basically looking for a way to get a request in fiddler and implement it directly in to my code in the format that fiddler gives it to me.(In fiddler I can save the request in .txt format. If I could use that same .txt format to send the request then it would be really helpful)
You need to create HttpClient instance and set the headers shown in the fiddler to the same values. Hope this helps. Your URL was HTTPS hence you will need to set for certificate validation OR you will have to set avoid certificate errors on the call.
// Create a client
HttpClient httpClient = new HttpClient();
// Add a new Request Message
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Put, "https://yoursitehere/");
// Add our custom headers
requestMessage.Headers.Add("User-Agent", "User-Agent-Here");
requestMessage.Headers.Add("Connection", "MIME-Type-Here");
requestMessage.Headers.Add("Cache-Control", "value-from-fiddler");
requestMessage.Headers.Add("Accept-Language", "value-from-fiddler");
requestMessage.Headers.Add("Accept-Encoding", "value-from-fiddler");
requestMessage.Headers.Add("Accept", "value-from-fiddler");
requestMessage.Headers.Add("User-Agent", "value-from-fiddler");
// Send the request to the server
HttpResponseMessage response = await httpClient.SendAsync(requestMessage);
// Just as an example I'm turning the response into a string here
string responseAsString = await response.Content.ReadAsStringAsync();
I wrote a webservice (web api 2) and tested it successfully with the http Client. One of the Services took a json string and validated it, and then returned an appropriate download stream.
Now though I found out that I Need to write a 3.5 Framework Client for handling the whole Transfer (posting the json data and then getting the file).
As example for getting a text with web Client:
private string GetTextFromUrl(string url, JObject jsonObject)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("content-type", "application/json");
return Encoding.ASCII.GetString(webClient.UploadData(url, Encoding.Default.GetBytes(jsonObject.ToString())));
}
Now though I'm a bit at a loss. From what I see with the webclient only OpenRead and DownloadFile return streams while everything else Returns a Byte Array.
Both though use only the URL and don't do any Posts (like upload data does). So I'm wondering there: Is there any possibility to post json data to a URL and receive a stream in Response with Framework 3.5? (not necessarily limited to webclient).
Edit:
To clarify as it was asked: The Client Posts a json string to the Server and receives a stream in Response. That is what I try to achieve (Client side wise).
I think you have 2 options but that is not really the problem. I think you are missing out on JSON.NET
Using WebClient
Post using webclient in .NET 3.5 is done as below by specifying headers and the "POST" method.
System.Net.WebClient client = new System.Net.WebClient();
client.Headers.Add("content-type", "application/json");//set content-type header here
string response = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"Data\": \"JSON DATA HERE\"}")));
Usually when you do the above, you should get a response from the upload method that you can assign to a variable 'response' and then use JSON.NET.
Please see this link here as well. He doesn't specify the method but uses JSON.NET and seems to work for him.
Using WebRequest
You could also try WebRequest. Please see this link for webrequest example
Hope this helps.
I need to generate an http request to the vimeo api as per step 2 in this page, which is given below.
PUT https://i.cloud.vimeo.com/video/518016424
.... binary data of your file in the body ....
I alredy have an access token for this. Suppose the access token is "qw21we34". How do I generate an http request, with the token in the header and binary data in the body.
I tried using WebClient() class as suggested here, but I cannot find a method to pass the OAuth access token with this type of request. Please note that there are no official libraries for Vimeo api that have this facility. Can anyone help?
For this you can use the WebClient() class. For the authentication, we need the access token from the previous request as well. I got it from my VimeoClient object called vc. That is up to you to figure out.
WebClient wb = new WebClient();
wb.Headers.Add("Authorization","Bearer" +vc.AccessToken);
var file = wb.DownloadData(new Uri(myimageurl));
var asByteArrayContent = wb.UploadData(new Uri(thumbnail_uri), "PUT", file);
var asStringContent = Encoding.UTF8.GetString(asByteArrayContent);
After sending this request, you should get a json response stating the success for asStringContent.
When making a call to my webapi running locally, I am passing data in the requestUri as base64 encoded Json of my serialized object, but getting StatusCode 400 at every turn.
How do I fix my request?
public class VerifyController : ApiController
{
// GET: api/Verify/jsonStringAddressOriginal
public AddressResult Get(string base64AddressOriginal)
The caller:
var requestUri = string.Format("api/verify/{0}", base64address);
Console.WriteLine("requestUri:\n{0}", requestUri);
HttpResponseMessage response = client.GetAsync(requestUri).Result;
requestUri:
api/verify/eyJDb21wYW55IjoiIiwiQWRkcmVzcyI6Ijc3NTAgQmVsZm9ydCBQYXJrd2F5IDIwMCIsI
kFkZHJlc3MyIjoiIiwiU3VpdGUiOiIiLCJDaXR5IjoiSmFja3NvbnZpbGxlIiwiU3RhdGUiOiJGTCIsI
lppcCI6IjMyMjU2IiwiUGx1czQiOiIiLCJMYXN0TGluZSI6IiIsIkNvdW50cnlDb2RlIjoiIiwiVXJiY
W5pemF0aW9uIjoiIiwiTGFzdE5hbWUiOiIiLCJQYXJzZWRBZGRyZXNzUmFuZ2UiOiIiLCJQYXJzZWRQc
mVEaXJlY3Rpb24iOiIiLCJQYXJzZWRTdHJlZXROYW1lIjoiIiwiUGFyc2VkU3VmZml4IjoiIiwiUGFyc
2VkUG9zdERpcmVjdGlvbiI6IiIsIlBhcnNlZFN1aXRlTmFtZSI6IiIsIlBhcnNlZFN1aXRlUmFuZ2UiO
iIiLCJQYXJzZWRSb3V0ZVNlcnZpY2UiOiIiLCJQYXJzZWRMb2NrQm94IjoiIiwiUGFyc2VkRGVsaXZlc
nlJbnN0YWxsYXRpb24iOiIifQ==
Error code: BadRequest
Reason: Bad Request
I think it's a malformed request but I don't know in what way. There seem to be no further properties of the response object detailing which error that the 400 Status Code represents. http://msdn.microsoft.com/en-us/library/azure/dd179357.aspx
This is my first WebApi so when answering, make no assumptions about my configuration.
VS2013 update 3, Web Api, using an HttpClient as the caller.
I didn't count the number of characters in your URI, but very long URIs (> 2000 characters) are likely to cause problems. Try making this a POST request and putting the base64 data into the request body.