I need to make an rpc to a thirh party API and send the following JSON
{
"jsonrpc":"2.0",
"id":"number",
"method":"login.user",
"params":{
"login":"string",
"password":"string"
}
}
I have created a method to make the rcp but i cannot get the correct JSON to be send
public JObject Post()
{
object[] a_params = new object[] { "\"login\" : \"test#test.ru\"", "\"password\": \"Password\""};
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://test.test.ru/v2.0");
webRequest.ContentType = "application/json; charset=UTF-8";
webRequest.Method = "POST";
JObject joe = new JObject();
joe["jsonrpc"] = "2.0";
joe["id"] = 1;
joe["method"] = "login.user";
if (a_params != null)
{
if (a_params.Length > 0)
{
JArray props = new JArray();
foreach (var p in a_params)
{
props.Add(p);
}
joe.Add(new JProperty("params", props));
}
}
string s = JsonConvert.SerializeObject(joe);
// serialize json for the request
byte[] byteArray = Encoding.UTF8.GetBytes(s);
webRequest.ContentLength = byteArray.Length;
WebResponse webResponse = null;
try
{
using (webResponse = webRequest.GetResponse())
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
}
}
}
}
catch (WebException webex)
{
using (Stream str = webex.Response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
var tempRet = JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
return tempRet;
}
}
}
catch (Exception)
{
throw;
}
}
With my code i'm getting the following JSON
{"jsonrpc":"2.0","id":1,"method":"login.user","params":["\"login\" : \"v.ermachenkov#mangazeya.ru\"","\"password\": \"AmaYABzP2\""]}
As i understand my error is that params is an array([]) instead of an object({}). Based on my method how can get the correct json?
I correct my mistake. The code shoukd be
JObject a_params = new JObject { new JProperty("login", "login"), new JProperty("password", "Password") };
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://test.test.ru/v2.0");
webRequest.ContentType = "application/json; charset=UTF-8";
webRequest.Method = "POST";
JObject joe = new JObject();
joe["jsonrpc"] = "2.0";
joe["id"] = "1";
joe["method"] = "login.user";
joe.Add(new JProperty("params", a_params));
Related
I'm trying to make POST to an external webapi sending "raw" data. I could successfully do it using for example Postman, but when I tried to do it in my MVC App, I get the following error: Specified value does not have a ':' separator. Parameter name: header.
This is my code for calling the webapi:
public UserCustom GetUserByToken(string pToken)
{
ResponseLogin vRespuesta = new ResponseLogin();
UserCarmocal vUsuarioFinal = null;
string vApiKey = ConfigurationManager.AppSettings["ApiKey"];
string vDirUser = ConfigurationManager.AppSettings["EndpointUsr"];
WebRequest request = WebRequest.Create(vDirUser);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("ApiKey", vApiKey);
string postData = pToken;
//I THINK THE ERROR IS IN THE NEXT LINE:
request.Headers.Add(postData);
using (Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
vRespuesta = new JavaScriptSerializer().Deserialize<ResponseLogin>(sr.ReadToEnd());
if (vRespuesta.status == "success")
{ vUsuarioFinal.FirstName = "Test"; }
}
}
return vUsuarioFinal;
}
Write the pToken variable to request stream
PSUEDO CODE
public UserCustom GetUserByToken(string pToken)
{
ResponseLogin vRespuesta = new ResponseLogin();
UserCarmocal vUsuarioFinal = null;
string vApiKey = ConfigurationManager.AppSettings["ApiKey"];
string vDirUser = ConfigurationManager.AppSettings["EndpointUsr"];
WebRequest request = WebRequest.Create(vDirUser);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("ApiKey", vApiKey);
var bytes = System.Text.Encoding.UTF8.GetBytes(pToken);
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
using (Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
vRespuesta = new JavaScriptSerializer().Deserialize<ResponseLogin>(sr.ReadToEnd());
if (vRespuesta.status == "success")
{ vUsuarioFinal.FirstName = "Test"; }
}
}
return vUsuarioFinal;
}
When I try to communicate with wallet-qt using C#, I got this error and don't know what I missing. I also try a lot solution from google but not succesfull Please help me thank.
Here is my code that I got an idea from this topichere: https://bitcoin.stackexchange.com/questions/5810/how-do-i-call-json-rpc-api-using-c/5811#5811?newreg=e26b1cb9e4b24ebdac98193efb5d3f4b
static void Main(string[] args)
{
var ret = InvokeMethod("getblockhash", 15);
}
public static JObject InvokeMethod(string a_sMethod, params object[] a_params)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:9998");
webRequest.Credentials = new NetworkCredential("user", "pass");
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
JObject joe = new JObject();
joe["jsonrpc"] = "1.0";
joe["id"] = "1";
joe["method"] = a_sMethod;
if (a_params != null)
{
if (a_params.Length > 0)
{
JArray props = new JArray();
foreach (var p in a_params)
{
props.Add(p);
}
joe.Add(new JProperty("params", props));
}
}
string s = JsonConvert.SerializeObject(joe);
// serialize json for the request
byte[] byteArray = Encoding.UTF8.GetBytes(s);
webRequest.ContentLength = byteArray.Length;
try
{
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
}
catch (WebException we)
{
//inner exception is socket
//{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 23.23.246.5:8332"}
throw;
}
WebResponse webResponse = null;
try
{
using (webResponse = webRequest.GetResponse())
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
}
}
}
}
catch (WebException webex)
{
using (Stream str = webex.Response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
var tempRet = JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
return tempRet;
}
}
}
catch (Exception)
{
throw;
}
}
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);
}
I have an OpenIdConnect Server I'm connecting to an I would like to forward token data the first time logging in to be stored on the server. Currently I'm doing this to forward the access token
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function () {
log(xhr.status, JSON.parse(xhr.responseText));
}
xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
xhr.send();
I want to send the Profile Data as well but I don't know the proper header.
How can I do something like this:
xhr.setRequestHeader("Authorization-Profile", "Bearer " + user.profile);
Does anyone know the proper header so I can add these claims to the access token.
Here is an example of what we did in one of our project:
Created a common API response class as below:
public class ApiCommonResponse
{
public object Object { get; set; }
public int httpStatus { get; set; }
public string httpErrorMessage { get; set; }
}
And a generic method to call GET and POST API endpoints. This method will map the response to the supplied data model and will return you the object.
public static ApiCommonResponse GetApiData<T>(string token, T dataModel, string apiEndPoint = null)
{
var responseText = "";
var apiCommonResponse = new ApiCommonResponse();
if (apiEndPoint != null)
{
var request = (HttpWebRequest)WebRequest.Create(apiEndPoint);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
request.Headers.Add("X-Api-Version", "");
try
{
var httpResponse = (HttpWebResponse)request.GetResponse();
var stream = httpResponse.GetResponseStream();
if (stream != null)
{
using (var streamReader = new StreamReader(stream))
{
responseText = streamReader.ReadToEnd();
}
}
}
catch (WebException we)
{
var stream = we.Response.GetResponseStream();
if (stream != null)
{
var resp = new StreamReader(stream).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
throw new Exception(obj.ToString());
}
}
}
var jsonSettings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore };
apiCommonResponse.Object = JsonConvert.DeserializeObject<T>(responseText, jsonSettings);
apiCommonResponse.httpStatus = 0;
return apiCommonResponse;
}
public static ApiCommonResponse PostApiData<T>(string username, string token, T dataModel, string apiEndPoint = null)
{
var apiCommonResponse = new ApiCommonResponse();
if (apiEndPoint == null) return null;
var webRequest = WebRequest.Create(apiEndPoint);
webRequest.Method = "POST";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
webRequest.Headers.Add("X-Api-Version", "");
using (var requeststreams = webRequest.GetRequestStream())
{
using (var sw = new StreamWriter(requeststreams))
{
sw.Write(JsonConvert.SerializeObject(dataModel));
}
}
try
{
var httpStatus = (((HttpWebResponse)webRequest.GetResponse()).StatusCode);
var httpMessage = (((HttpWebResponse)webRequest.GetResponse()).StatusDescription);
using (var s = webRequest.GetResponse().GetResponseStream())
{
if (s == null) return null;
using (var sr = new StreamReader(s))
{
var responseObj = sr.ReadToEnd();
if (!string.IsNullOrEmpty(responseObj))
{
apiCommonResponse = JsonConvert.DeserializeObject<ApiCommonResponse>(responseObj);
}
}
apiCommonResponse.httpStatus = (int)httpStatus;
apiCommonResponse.httpErrorMessage = httpMessage;
apiCommonResponse.Object = apiCommonResponse.Object;
}
}
catch (WebException we)
{
var stream = we.Response.GetResponseStream();
if (stream != null)
{
var resp = new StreamReader(stream).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
throw new Exception(obj.ToString());
}
}
return apiCommonResponse;
}
I want to post a request on server using POST and webrequest?
I need to pass parameters as well while posting?
how can i pass the parameters while posting?
How can i do that???
Sample code...
string requestBody = string.Empty;
WebRequest request = WebRequest.Create("myursl");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
//request.ContentLength = byte sXML.Length;
//System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
//sw.Write(sXML);
//sw.Close();
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
if (res != null)
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), true))
{
ReturnBody = sr.ReadToEnd();
StringBuilder s = new StringBuilder();
s.Append(ReturnBody);
sr.Close();
}
}
if (ReturnBody != null)
{
if (res.StatusCode == HttpStatusCode.OK)
{
//deserialize code for xml and get the output here
string s =ReturnBody;
}
}
NameValueCollection keyValues = new NameValueCollection();
keyValues["key1"] = "value1";
keyValues["key2"] = "value2";
using (var wc = new WebClient())
{
byte[] result = wc.UploadValues(url,keyValues);
}
you can try with this code
string parameters = "sample=<value>&other=<value>";
byte[] stream= Encoding.UTF8.GetBytes(parameters);
request.ContentLength = stream.Length;
Stream newStream=webRequest.GetRequestStream();
newStream.Write(stream,0,stream.Length);
newStream.Close();
WebResponse webResponse = request.GetResponse();