I am using 4shared rest api, and working on edit file information by http put. I coded like this:
public void UpdateFile(string fileID, string accessToken, int uniqueID)
{
Action<string> OnResponse = this.OnFileUpdate;
string uri = string.Format("http://api.4shared.com/v0/files/fileID.json?oauth_token= {1}&UniqueID={2}",accessToken,uniquesID);
uri=uri + "&name=mayank&description=This is for testing.";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(uri));
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetResponse(delegate(IAsyncResult result)
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
string response1 = reader.ReadToEnd();
onResponseGot(response1);
}
}
}, null);
}
private void OnFileUpdate(string result)
{
if (!string.IsNullOrEmpty(result))
{
//do some code after file updates.
}
}
Now I am getting response but with same old values. I also tried to test it on api console but result is same. I didn't find out the problem.
Related
I'm trying to get the response from an http api rest link, but i don't know why, the response is empty, even testing the endpoint on postman and in my browser, that returns the correct. The code i'm using for getting the response is:
private static string connect(string url, string method, string data)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.ContentType = "application/json";
request.Accept = "application/json";
if (data.Length > 0)
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();
}
}
using (WebResponse response = request.GetResponse())
{
using (Stream strReader = response.GetResponseStream())
{
if (strReader == null) return "";
using (StreamReader objReader = new StreamReader(strReader))
{
return JsonConvert.DeserializeObject<Response>(objReader.ReadToEnd()).data; //objReader.ReadToEnd();
}
}
}
}
And calling it like this:
String response = connect("http://31.214.245.211:8080/ProjectM-WS/webservice/rest/ping", "GET", "");
Any idea of where I can be wrong?
Thank you for the help!
Thought that didn't work, that's becouse i commented it, but now it does.
private static string connect(string url, string method, string data)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.ContentType = "application/json";
request.Accept = "application/json";
if (data.Length > 0)
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();
}
}
using (WebResponse response = request.GetResponse())
{
using (Stream strReader = response.GetResponseStream())
{
if (strReader == null) return "";
using (StreamReader objReader = new StreamReader(strReader))
{
return objReader.ReadToEnd();
}
}
}
}
I have the access token. How can I make a request using the token in c#?
Here is what I have tried unsuccessfully resulting in error 400 Bad Request.
Note: the url was copied from the YQL console
public static void Request(string token)
{
var request =
WebRequest.Create(
#"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20fantasysports.leagues%20where%20league_key%3D'371.l.4019'&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
request.Headers["Authorization"] = $"Bearer {token}";
request.Method = "GET";
request.ContentType = "application/xml;charset=UTF-8";
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
if (stream == null) return;
var reader = new StreamReader(stream, Encoding.UTF8);
var responseString = reader.ReadToEnd();
}
}
}
I am using a C# WebAPI project which would call an external API based on its URL. However, when I am trying to retrieve the data back, it hangs/freezes.
The code where it stops is:
var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
I don't understand why it is stopping though. Could it be interfering with the API request I am also making? When I run this code as part of a unit test, I would get a response back within seconds. I don't think it is the API service itself, I think it is my code. I have already tried various API URLS. None of them work.
My full code is:
public static async Task<string> CallWebAPi<T>(string url)
{
string returnValue;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
Stream stream = response.GetResponseStream();
StreamReader strReader = new StreamReader(stream);
returnValue = await strReader.ReadToEndAsync();
return returnValue;
}
Any help would be appreciated.
Possible deadlock ConfigureAwait(false), here are a good explanation from Stephen on what cause deadlocks.
var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null).ConfigureAwait(false);
As a workaround you can use the synchronous functions, create a Task and await this task:
var response = await Task.Run(() =>
{
return (HttpWebResponse)request.GetResponse();
});
This is how i do my Request. Each Part is in an own Function. Its create the Request and you can get the Response synchronous.
public HttpWebRequest CreateRequest(string Url, string Method, string ContentType, object Content, List<RequestHeader> headers)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = Method;
if (!string.IsNullOrWhiteSpace(ContentType)) request.ContentType = ContentType;
else if(Content != null) request.ContentType = "application/json";
if (Content != null)
{
var postData = Newtonsoft.Json.JsonConvert.SerializeObject(Content);
var data = Encoding.ASCII.GetBytes(postData);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
foreach(RequestHeader header in Headers)
{
request.Headers.Add(header.Type, header.Value);
} //class at the end.
return request;
}
public string GetResponse(HttpWebRequest request)
{
var retval = "";
try
{
var response = (HttpWebResponse)request.GetResponse();
retval = ReadResponse(response);
response.Close();
}
catch (Exception ex)
{
resolveException(ex.Message);
}
return retval;
}
public string ReadResponse(HttpWebResponse response)
{
var retval = "";
try
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var responseText = reader.ReadToEnd();
retval = responseText;
}
}
catch (Exception ex)
{
resolveException(ex.Message);
}
return retval;
}
public class RequestHeader
{
public HttpRequestHeader Type { get; set; }
public string Value { get; set; }
}
you dont need Task.Factory.FromAsync. HttpWebRequest already supports asynchronous operations.
You have defined a generic method CalWebApi<T> but have never used a generic type
if your operation is async, use this.
public async Task<T> CalWebApiAsync<T>(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
using (var response = await request.GetResponseAsync())
{
using (var responseStream = response.GetResponseStream())
{
using (var streamReader = new StreamReader(responseStream))
{
var stringResult = await streamReader.ReadToEndAsync();
T objectResult = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(stringResult);
return objectResult;
}
}
}
}
var result = await CallWebApiAsync<YourType>("exteranlapiurl");
if your operation is not async, use this..
public T CalWebApi<T>(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var streamReader = new StreamReader(responseStream))
{
var stringResult = streamReader.ReadToEnd();
T objectResult = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(stringResult);
return objectResult;
}
}
}
}
var result = CallWebApi<YourType>("exteranlapiurl");
WebRequest request = WebRequest.Create(url);
WebRequest.DefaultWebProxy = null;
request.Proxy = null;
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
The above code not able to read/download the following webpages:
1) https://en.wikipedia.org/wiki/Unified_Payments_Interface
2) http://www.npci.org.in/UPI_Background.aspx
This may help you below code contains for both to get and post data:
public static string PostContent(this Uri url, string body, string contentType = null)
{
var request = WebRequest.Create(url);
request.Method = "POST";
if (!string.IsNullOrEmpty(contentType)) request.ContentType = contentType;
using (var requestStream = request.GetRequestStream())
{
if (!string.IsNullOrEmpty(body)) using (var writer = new StreamWriter(requestStream)) { writer.Write(body); }
using (var response = request.GetResponse() as HttpWebResponse)
{
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
public static string GetContent(this Uri url)
{
WebClient client = new WebClient();
try
{
using (client)
{
client.Encoding = Encoding.UTF8;
return client.DownloadString(url);
}
}
catch (WebException)
{
return "";
}
finally
{
client.Dispose();
client = null;
}
}
please note that .aspx file extension design the server-side page and in consequence you will be able to download only the html page that display when you navigate on these sites (this is the same for .php files).
but if you want to download the frontend view this should work :
using System.Net;
...
WebClient client = new WebClient();
client.DownloadFile("Your url","download location");
Following code returns entire JSON objects but I need to Filter to some specific Object, for example I need to get only the "layers" or tiltle can you please let me know how to do this is C#?
Do I have to create an HttpWebRequestobject for this? if so where should I pass the requested data?
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
Console.WriteLine(json);
}
I already tried this but it is also returning everything
class Program
{
private const string URL = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson";
private const string DATA = #"{{""layers"":""Layers""}}";
static void Main(string[] args)
{
CreateObject();
}
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = DATA.Length;
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write(DATA);
}
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
Console.WriteLine(response);
Console.ReadLine();
}
}
}
}
catch (Exception e)
{
Console.WriteLine("-----------------");
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
If you need the info related to the layers array object then you can use following code
using (var wc = new WebClient())
{
string json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
dynamic data = Json.Decode(json);
Console.WriteLine(data.layers[0].id);
Console.WriteLine(data.layers[0].name);
Console.WriteLine(data.documentInfo.Title);
}