I did a POST request code pointing to an API to do an automatic exchange program.
Here is the code:
string webAddr = "https://shapeshift.io/shift";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"withdrawal\" : \"***ADDRESS WITH LETTER AND NUMBER***\", \"pair\" : \"eth_xmr\" }";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
And after executing the code, I'm getting this in the console
{"orderId":"1f90346c-c6d4-4d89-a24c-78b2bbdb6292","deposit":"0x534aa684274b4711f65b2d0e2e403cb169201255","depositType":"ETH","withdrawal":"***ADDRESS WITH LETTER AND NUMBER***","withdrawalType":"XMR"
Now, I want to put the address from deposit that I'm getting from the API into a string variable. I tried some code but I can't make it working. So how can I put this address in a string variable ?
You could deserialize the response and get from there that you want. In order to do so you could define a class, let's name it ApiResponse:
public class ApiResponse
{
[JsonProperty("orderId")]
public string orderId { get; set; }
[JsonProperty("deposit")]
public string deposit { get; set; }
[JsonProperty("depositType")]
public string depositType { get; set; }
[JsonProperty("withdrawal")]
public string withdrawal { get; set; }
[JsonProperty("withdrawalType")]
public string withdrawalType { get; set; }
}
and then after
var responseText = streamReader.ReadToEnd();
make the deserialization:
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(responseText);
I have used the Json.NET library. So if you haven't isntall it, you should do so or you could make use of another library and change correspondingly the above code.
Related
I'm trying to parse data from a response using httpwebrequest, which is in JSON format, I've tried to use JSON.Net but seem to be having no luck, I'm open to using Regex if need be.
Example of current code -
var request = (HttpWebRequest)WebRequest.Create("https://www.example.com/response");
request.Method = "GET";
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8;"
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic data = JOBject.Parse(response);
Console.WriteLine(data.name);
Example of response in full -
[{"_id":"hello","_source":{"name":"hello","example":"hey"},"_type":"_doc"}]
Try This:
WebRequest webRequest = WebRequest.Create("https://www.example.com/response");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
if (response.StatusDescription == "OK")
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// Display the content.
dynamic data = JObject.Parse(responseFromServer);
Console.Write(data.name);
}
You can create these two classes like this.
public class Source
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("example")]
public string Example { get; set; }
}
public class ResponseObject
{
[JsonProperty("_id")]
public string Id { get; set; }
[JsonProperty("_source")]
public Source Source { get; set; }
[JsonProperty("_type")]
public string Type { get; set; }
}
And then parse your response like this
var data = JsonConvert.DeserializeObject<ResponseObject>(response);
Hope this will help you
I can get accesstoken but I don't know how to get username and uuid from accesstoken, when I login it's gave me something like that
{"accessToken":"123","clientToken":"123","selectedProfile":{"id":"123","name":"playername"},"availableProfiles":[{"id":"123","name":"playername"}]}
Thanks!
private vstrong textoid Signin_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
try
{
bool isSignedIn = false;
if (isSignedIn == true)
{
var request = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/invalidate");
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
dynamic json = JsonConvert.SerializeObject(new
{
accessToken = Settings.Default.accessToken,
clientToken = Settings.Default.clientToken
});
}
Settings.Default.UUID = null;
Settings.Default.accessToken = null;
Settings.Default.clientToken = null;
}
else
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
dynamic json = JsonConvert.SerializeObject(new
{
agent = new
{
name = "Minecraft",
version = 1
},
username = email.Text,
password = password.Password
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
ACCESS_TOKEN = result;
}
}
}
catch (WebException)
{
MessageBox.Show("Login failed. Invalid username or password.");
}
}
string ACCESS_TOKEN;
public string GetAccessToken()
{
return ACCESS_TOKEN;
}
That is a JSON response, which you will need to deserialize to use most effectively. You can do this with the following code:
var loginResponse = JsonConvert.DeserializeObject<LoginResponse>(result);
Now, the MinecraftLoginResponse will need to be a class you create yourself, unless there is a library that you are using for this. JSON consists of variable value combinations, the values after the ':', separated by commas. {} denote an object, and [] a collection.
In the minecraft response, you have two objects; the response itself, and then the Profile object. C# code of this response is:
public class Profile
{
public string id { get; set; }
public string name { get; set; }
}
public class LoginResponse
{
public string accessToken { get; set; }
public string clientToken { get; set; }
public Profile selectedProfile { get; set; }
public List<Profile> availableProfiles { get; set; }
}
I made the above by running the example response through this website, then removing the SelectedProfile and AvailableProfile as these are, logically, going to be the same thing. (Selected will be one of the available profiles).
I am trying to send a request from server side to my API, here is my code from Server
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:59606/api/values/UserCheck");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"username\":\"User\"," +
"\"password\":\"Mypassword\"," +
"\"logonfrom\":\"DOMAIN\\DomainName\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadLine();
}
May API code are below:
[HttpPost]
[ActionName("UserCheck")]
public bool UserCheck([FromBody]User value)
{
ContextType CT = ContextType.Domain;
if (value.logonfrom.Split('\\')[0] == "DOMAIN")
{
CT = ContextType.Domain;
}else if(value.logonfrom.Split('\\')[0] == "MACHINE")
{
CT = ContextType.Machine;
}else
{
return false;
}
return CheckCredentials(value.username, value.password, CT,value.logonfrom.Split('\\')[1]);
}
when my request reach the Action of UserCheck, the value of
([FromBody]User value)
is null
my Class for the User is below
public class User
{
public string username { get; set; }
public string password { get; set; }
public string system { get; set; }
public string IP { get; set; }
public string logonfrom { get; set; }
}
BUT once i remove the logonfrom variable from json there is no error, i mean the parameter (value) successfully captures the content i sent.
Thanks
use the following peace of code.
string json = JsonConvert.SerializeObject(new { username = "afsa", password = "fsaf", system = "fsaf", ip = "fsf", logonfrom ="fsfsd"});
I am having trouble sending a list of objects to a webapi controller.
This is the controler:
[AcceptVerbs("POST")]
public string syncFoodData(List<intakeSync> str)
{
string apikey = Request.Headers.GetValues("api_key").ToArray()[0];
return "data syncronised";
}
This is the class:
public class intakeSync
{
public int memberID { get; set; }
public Double size { get; set; }
public string food { get; set; }
public string token { get; set; }
public string time { get; set; }
public string date { get; set; }
public string nocatch { get; set; }
public string calories { get; set; }
}
The value of str is always null.
this is the webmethod that sends the httprequest to the webapi
public static string syncIntakeData(string token, string[] syncString)
{
JavaScriptSerializer js = new JavaScriptSerializer();
List<intakeSync> str = new List<intakeSync>();
for (int i = 0; i <= syncString.Length - 1; i++)
{
str.Add(js.Deserialize<intakeSync>(syncString[i]));
}
string url = URI + "/api/Food/?str=" +js.Serialize(str);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("api_key", token);
Stream requestStream = request.GetRequestStream();
StreamReader read = new StreamReader(request.GetResponse().GetResponseStream());
string dat = read.ReadToEnd();
read.Close();
request.GetResponse().Close();
return dat;
}
You can use this :
Request body in Json
[{id:1, nombre:"kres"},
{id:2, nombre:"cruz"}]
Api Rest .net C#
public string myFunction(IEnumerable<EntitySomething> myObj)
{
//...
return "response";
}
I don't know really how your JSON is serialized in the line js.Serialize(str); I suspect that this line is the core problem. Sending JSON is better suited in the POST Request body than in the query string. Anyways, I think that HttpClient is better suited for working with WebApi because it offers symmetric programming experience. You could try something like that with HttpClient :
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(URI);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("api_key", token);
var content = new ObjectContent(syncString, new JsonMediaTypeFormatter());
var result = client.PostAsync("/api/Food/", content).Result;
}
here am facing little bit problem while deserializing json string to list
json string : Result of restful service
"\"{\\"UName\\":\\"prasad\\",\\"LastName\\":\\"k\\",\\"FirstName\\":\\"sai\\"}\""
and i want to convert this json string to genric list
my list :
public class _TempUser
{
public string UName
{
get;
set;
}
public string LastName
{
get;
set;
}
public string FirstName
{
get;
set;
}
}
Error is
Error converting value "{"UName":"prasad","LastName":"k","FirstName":"sai"}" to type 'System.Collections.Generic.List`1[loginServices.Login_Service+_TempUser]'. Path '', line 1, position 70.
code : for calling restful service
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http ://IpAddress:Post/Login/RestServiceName.svc/RestMethoName");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json =JsonConvert.SerializeObject(Req);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
List<_TempUser> List = new List<_TempUser>();
List = JsonConvert.DeserializeObject<List<_TempUser>>result
}
}
any modifications or suggestions plz
First your json string must be like this:
"{\"UName\":\"prasad\",\"LastName\":\"k\",\"FirstName\":\"sai\"}"
NOT
"\"{\\"UName\\":\\"prasad\\",\\"LastName\\":\\"k\\",\\"FirstName\\":\\"sai\\"}\""
Then you can parse it using:
string entry = "{\"UName\":\"prasad\",\"LastName\":\"k\",\"FirstName\":\"sai\"}";
var parsedObject = JsonConvert.DeserializeObject<JObject>(entry);
foreach (var dataset in parsedObject.Properties())
{
Console.WriteLine(dataset.Name);
}
I am using Newtonsoft.Json and Newtonsoft.Json.Linq for the parsing.