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);
}
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 am trying to Access the private Poloniex trading API in Unity C# but am getting the error "invalid command" I have my API Key and Secret authorized on Poloniex for the Trading API but can't seem to get access with my current code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Security.Cryptography;
public class PolonScript : MonoBehaviour {
public TextMesh OutputText;
const string _apiKey = "---Key---";
const string _apiSecret = "---secret---";
void Start () {
string nonce = DateTime.Now.ToString("HHmmss");
string myParam = "command=returnBalances&nonce=" + nonce;
const string WEBSERVICE_URL = "https://poloniex.com/tradingApi";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.Timeout = 12000;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Headers.Add("Key", _apiKey);
webRequest.Headers.Add("Sign", genHMAC(myParam));
webRequest.Headers.Add("command", "returnBalances");
webRequest.Headers.Add("nonce", nonce.ToString());
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
OutputText.text = jsonResponse.ToString();
}
}
}
}
catch (Exception ex)
{
OutputText.text = ex.ToString();
}
} //end-of-start()
Here is my current signing method which I am quite sure has a mistake (Human error) within, am I doing something wrong obliviously here?
private string genHMAC(string message)
{
byte [] APISecret_Bytes = System.Text.Encoding.UTF8.GetBytes(_apiSecret);
byte [] MESSAGE_Bytes = System.Text.Encoding.UTF8.GetBytes(message);
var hmac = new HMACSHA512(APISecret_Bytes);
var hashmessage = hmac.ComputeHash(MESSAGE_Bytes);
var sign = BitConverter.ToString(hashmessage).Replace("-", "").ToLower();
return sign;
}
}
Poloniex Command should not be sent in the header, you should send it as a POST parameter, that's why it's responding "invalid command". Take a look at this answer to see how you send POST parameters in c#:How to add parameters into a WebRequest?
Here's an example of how your Start method should look like:
void Start()
{
string nonce = DateTime.Now.ToString("HHmmss");
string myParam = "command=returnBalances&nonce=" + nonce;
const string WEBSERVICE_URL = "https://poloniex.com/tradingApi";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.Timeout = 12000;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Headers.Add("Key", _apiKey);
webRequest.Headers.Add("Sign", genHMAC(myParam));
byte[] dataStream = Encoding.UTF8.GetBytes($"command=returnBalances&nonce={nonce.ToString()}");
webRequest.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
OutputText.text = jsonResponse.ToString();
}
}
}
}
catch (Exception ex)
{
OutputText.text = ex.ToString();
}
}
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");
Here is my proxy code.
[Runtime.InteropServices.DllImport("wininet.dll", SetLastError = true)]
private static bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);
public struct Struct_INTERNET_PROXY_INFO
{
public int dwAccessType;
public IntPtr proxy;
public IntPtr proxyBypass;
}
private void UseProxy(string strProxy)
{
const int INTERNET_OPTION_PROXY = 38;
const int INTERNET_OPEN_TYPE_PROXY = 3;
Struct_INTERNET_PROXY_INFO struct_IPI = default(Struct_INTERNET_PROXY_INFO);
struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy);
struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local");
IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI));
Marshal.StructureToPtr(struct_IPI, intptrStruct, true);
bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, System.Runtime.InteropServices.Marshal.SizeOf(struct_IPI));
}
private void Button1_Click(System.Object sender, System.EventArgs e)
{
Label4.Text = (TextBox1.Text + ":" + TextBox2.Text);
}
This code works fine with a windows from app. I tried using it in a console app and checked my ip but it did not work. Here is how i used it in a console app,
static void Main()
{
Console.WriteLine("Ip before Proxy /r/n");
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3 = a2.Split('<');
string a4 = a3[0];
Console.WriteLine(a4);
UseProxy("219.93.183.106:8080");
Console.WriteLine("Ip after Proxy /r/n");
HTTPGet req1 = new HTTPGet();
req1.Request("http://checkip.dyndns.org");
string[] a1 = req1.ResponseBody.Split(':');
string a21 = a1[1].Substring(1);
string[] a31 = a21.Split('<');
string a41 = a31[0];
Console.WriteLine(a41);
Console.ReadLine();
}
HTTPGet is a class i got from : Get public/external IP address?
I want the proxy to work with the console app. I am not sure what is the problem
I will also run multiple instances of program so I want each console using one proxy and it should only affect the browsing of the console and not whole computer.
Proxies will have no authentication.
Here is my own HTTPBase class which handles all the http requests for the whole app,
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Web;
using System.Runtime.InteropServices;
public class HTTPBase
{
private CookieContainer _cookies = new CookieContainer();
private string _lasturl;
private int _retries = 3;
private string _useragent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; FunWebProducts; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; InfoPath.1)";
public HTTPBase()
{
ServicePointManager.UseNagleAlgorithm = false;
ServicePointManager.Expect100Continue = false;
}
public void ClearCookies()
{
this._cookies = new CookieContainer();
}
public static string encode(string str)
{
// return System.Net.WebUtility.HtmlEncode(str);
return HttpUtility.UrlEncode(str);
//return str;
}
public string get(string url)
{
for (int i = 0; i < this._retries; i++)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = this._useragent;
request.CookieContainer = this._cookies;
if (this._lasturl != null)
{
request.Referer = this._lasturl;
}
else
{
request.Referer = url;
}
this._lasturl = url;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
catch (Exception exception)
{
if ((i + 1) == this._retries)
{
throw exception;
}
}
}
throw new Exception("Failed");
}
public string post(string url, string postdata)
{
for (int i = 0; i < this._retries; i++)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
if (this._lasturl != null)
{
request.Referer = this._lasturl;
}
else
{
request.Referer = url;
}
this._lasturl = url;
request.Method = "POST";
request.UserAgent = this._useragent;
request.CookieContainer = this._cookies;
request.ContentLength = postdata.Length;
using (Stream stream = request.GetRequestStream())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(postdata);
}
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream stream2 = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream2))
{
return reader.ReadToEnd();
}
}
}
catch (Exception exception)
{
if (this._lasturl.Contains("youtuberender.php"))
{
return "bypassing youtube error";
}
if ((i + 1) == this._retries)
{
throw exception;
}
}
}
throw new Exception("Failed");
}
public string post(string url, string postdata, string referer)
{
for (int i = 0; i < this._retries; i++)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = referer;
this._lasturl = url;
request.Method = "POST";
request.UserAgent = this._useragent;
request.CookieContainer = this._cookies;
request.ContentLength = postdata.Length;
using (Stream stream = request.GetRequestStream())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(postdata);
}
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream stream2 = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream2))
{
return reader.ReadToEnd();
}
}
}
catch (Exception exception)
{
if (this._lasturl.Contains("youtube.com"))
{
return "bypassing youtube error";
}
if ((i + 1) == this._retries)
{
throw exception;
}
}
}
throw new Exception("Failed");
}
public string XmlHttpRequest(string urlString, string xmlContent)
{
string str = null;
HttpWebRequest request = null;
HttpWebResponse response = null;
request = (HttpWebRequest)WebRequest.Create(urlString);
try
{
byte[] bytes = Encoding.ASCII.GetBytes(xmlContent);
request.Method = "POST";
request.UserAgent = this._useragent;
request.CookieContainer = this._cookies;
request.ContentLength = bytes.Length;
request.Headers.Add("X-Requested-With", "XMLHttpRequest");
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
using (Stream stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream stream2 = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream2))
{
str = reader.ReadToEnd();
}
}
}
response.Close();
}
catch (WebException exception)
{
throw new Exception(exception.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
finally
{
response.Close();
response = null;
request = null;
}
return str;
}
public string UserAgent
{
get
{
return this._useragent;
}
set
{
this._useragent = value;
}
}
}
}
So I want to be able to add the proxy in this code. I will pass a variable from main form which will have the proxy:port format and I want this code to use the proxy. I am new to these proxy things and having some confusions.
I use net framework 4.0 in VS 12.
You can use WebRequest.DefaultWebProxy
WebRequest.DefaultWebProxy = null;
using (WebClient wc = new WebClient())
{
string html = wc.DownloadString("http://checkip.dyndns.org");
Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}
WebRequest.DefaultWebProxy = new WebProxy("219.93.183.106", 8080);
using (WebClient wc = new WebClient())
{
string html = wc.DownloadString("http://checkip.dyndns.org");
Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}
Or you can set proxy explicitly:
using (WebClient wc = new WebClient { Proxy = null })
{
string html = wc.DownloadString("http://checkip.dyndns.org");
Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}
using (WebClient wc = new WebClient { Proxy = new WebProxy("219.93.183.106", 8080) })
{
string html = wc.DownloadString("http://checkip.dyndns.org");
Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}
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.