Trying to write a method to push a TX, I never programatically done a POST request, so I'm clearly messing somewhere bad.
According to the documentation from blockr, I'm supposed to do this:
To publish a transaction make a POST (!) request with your transaction
hex to the push API.
Using curl this would be like (shell example):
curl -d '{"hex":"TX_HASH"}' http://btc.blockr.io/api/v1/tx/push
I'm getting 500 errors left and right.
I'm doing this on C#, could someone help?
Post("http://btc.blockr.io/api/v1/tx/push", "hex", HexString);
public static void Post(string RequestURL, string Post1, string Post2)
{
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data[Post1] = Post2;
var response = wb.UploadValues(RequestURL, "POST", data);
}
}
By default UploadValues doesn't format the data in json, you could format it yourself:
public static void Post(string RequestURL, string Post1, string Post2)
{
using (var wb = new WebClient())
{
var data = string.Format("{0}\"{1}\":\"{2}\"{3}", "{", Post1, Post2, "}");
var response = wb.UploadString(RequestURL, "POST", data);
}
}
Or use a JSON serializer such as NewtonSoft
Related
I have a rest endpoint that accepts a single custom object parameter containing two properties.
Let's call the param InfoParam
public class InfoParam
{
public long LongVar { get; set; }
public string StringVar { get; set; }
}
My code I have is as follows:
infoParam.LongVar = 12345678;
infoParam.StringVar = "abc"
var myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
var content = string.Empty;
using (var theResponse = (HttpWebResponse)MyRequest.GetResponse())
{
using (var stream = theResponse.GetResponseStream())
{
using (var sr = new StreamReader(stream))
{
content = sr.ReadToEnd();
}
}
}
So I have the InfoParam variable, with the two values, but I can't figure out where to pass it in to the REST endpoint.
You need to turn the object into a stream of bytes that can be added to the Request stream - which will in turn be sent as the HTTP POST body. The format of these bytes needs to match what the server expects. REST endpoints usually expect these bytes to resemble JSON.
// assuming you have added Newtonsoft.JSON package and added the correct using statements
using (StreamWriter writer = new StreamWriter(myRequest.GetRequestStream()) {
string json = JsonConvert.SerializeObject(infoParam);
writer.WriteLine(json);
writer.Flush();
}
You'll probably want to set various other request parameters, like the Content-Type header.
You have to write it int the `Content (and set content-type). Check out How to: Send data by using the WebRequest class
The recommendation is to use System.Net.Http.HttpClient instead.
Please note that you should know what content the server expects ('application/x-www-form-urlencoded`, json, etc.)
The following snippet is from POST JSON data over HTTP
// Construct the HttpClient and Uri. This endpoint is for test purposes only.
HttpClient httpClient = new HttpClient();
Uri uri = new Uri("https://www.contoso.com/post");
// Construct the JSON to post.
HttpStringContent content = new HttpStringContent(
"{ \"firstName\": \"Eliot\" }",
UnicodeEncoding.Utf8,
"application/json");
// Post the JSON and wait for a response.
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
uri,
content);
// Make sure the post succeeded, and write out the response.
httpResponseMessage.EnsureSuccessStatusCode();
var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
Debug.WriteLine(httpResponseBody);
In your case the content would be something like this
HttpStringContent content = new HttpStringContent(
JsonConvert.SerializeObject(infoParam), // using Json.Net;
UnicodeEncoding.Utf8,
"application/json");
Don't know why a web request return HTML instead JSON. Can anyone please help.
private void Test()
{
string url = "https://www.netonnet.no/Category/GetFilteredCategory";
string json = "{'sectionId':'10978','filter': '[]','sortOrder':-1,'sortBy':0,'pageSize':96,'listType':'10'}";
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(url, "POST", json);
}
Debug.WriteLine(result);
}
When your asking an you want it in a specific format you should add
client.Headers[HttpRequestHeader.Accept] = "application/json";
This will tell the API that you want it in json, but this only works if they can give it to you in that format.
And like Amit Kumar Ghosh said in a comment above, it seems like they don't serve json.
I have been stuck in trying figure out the syntax for a particular scenario.
Scenario: When I give a JSON string as argument in the URL, I want the url to consume an API and retrieve the details from that API, as per the given input.
My project needs deserialization into c# so, I used JSON.NET for the same.
Say: input is - Profile-id : 123456789
The output should consume details pertaining to that Pid and display.
The i/p given in url:
https://www.docscores.com/widget/api/org-profile/demo-health/npi/123456789
The expected o/p:
json string
What i have been doing is :
string url = "https://www.docscores.com/widget/api/org-profile/demo-health/npi/?profile-id=ShowProfile";
string data = GET(url);
dynamic jsonDe = JsonConvert.DeserializeObject(data);
var phyRatings = Convert.ToString(jsonDe.profile.averageRating);
Console.WriteLine(phyRatings);
public string ShowProfile(string pid)
{
}
public static string GET(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string data = reader.ReadToEnd();
reader.Close();
stream.Close();
return data;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return null;
}
So, when I pass profile-id as 123456789 in the url, I want the syntax to extract other info with this Profile-id
I AM totally confused with the syntax in C#. How can I pass the argument and write inside the ShowProfile function? I searched everywhere but not able to find the correct syntax.
Can someone please tell me if this is the right way to do it?
EDIT: Sounds like you have two questions here. First is how to pass your Profile-Id in the URL, and the second is how to deserialize the JSON result into a C# object. But let me know if I'm misunderstanding.
For passing 123456789 as your profile ID, you just need to concatenate it into the URL string. So you might have
public string ShowProfile(string pid)
{
ProfileInfo info = GET(pid);
// Do what you want with the info here.
}
public static ProfileInfo GET(int profileId)
{
try
// Note this ends in "=" now.
string basePath = "/widget/api/org-profile/demo-health/npi/?profile-id=";
string path = basePath + profileId.ToString();
//...
ProfileInfo would be your custom class to match the JSON structure.
Then to deserialize the result, in your GET() method, you might instead try calling the service using HttpClient from the Microsoft.AspNet.WebApi.Client NuGet package, and then read that directly into a C# object whose structure maps to the JSON response you get (see example below). Your GET() method could then return that object, and then it'd be trivial for the ShowProfile() method to read the properties you want from that C# object.
public static ProfileInfo GET(int profileId)
{
try
{
// Note this ends in "=" now.
string basePath = "/widget/api/org-profile/demo-health/npi/?profile-id=";
string path = basePath + profileId.ToString();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.docscores.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
ProfileInfo info = await response.Content.ReadAsAsync<ProfileInfo>();
return info;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return null;
}
More code and info at MSDN: Calling a Web API From a .NET Client in ASP.NET Web API 2 (C#)
I have problem with connect to JSON server.
In user-manual:
The Interface is implemented as a standard HTTP Service. Using the service requires an authentication through the “Login” method. A Session Id is returned on success which has to be passed on every function call unless otherwise stated.
The expected data format when sending or receiving data is JSON.
All data must be passed using POST.
The session Id is of type Guid
Example:
Login
Description: Used to authenticate a user.
Url: /Login
Signature: Guid Login(string id, string username, string password)
END OF MANUAL
I wrote this code:
var webAddr = "https://xxx/Login";
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 = "{\"Login\":[{"
+ "\"id\" : 1213213,"
+ "\"username\" : asdasdasd,"
+ "\"password\" : \"adasdsadasd\","
+ "}]}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
MessageBox.Show(result.ToString());
}
And message is: Method not allowed.
How can I send and recive data from this serwer?
You are formatting your JSON incorrectly. The JSON should look like this:
{"id":"1213213","username":"asdasdasd","password":"adasdsadasd"}
Notice: quotes around each name and value. And "Login" should not be part of the JSON.
However, the problem is really that you are doing this all manually. Instead, let .NET format the JSON for you and handle the HTTP request. To do this, create a structure for the arguments:
class Login
{
public string id { get; set; }
public string username { get; set; }
public string password { get; set; }
}
Use NuGet to add references to "Json.Net" and "Microsoft ASP.NET Web API Client Libraries." Now you can write this:
static async Task Login()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.censored.de/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.Timeout = TimeSpan.FromSeconds(30);
Login l = new Login() { id = "12345", password = "abcde", username = "safsdfasdf" };
var sTemp = JsonConvert.SerializeObject(l); // DEBUG: Just so I can see the JSON
var response = await client.PostAsJsonAsync("/censored/Service.svc/Login", l);
Guid g;
if (response.IsSuccessStatusCode)
{
g = await response.Content.ReadAsAsync<Guid>(); // This gives you the GUID
}
//DEBUG:
// var rawResponse = await response.Content.ReadAsStringAsync();
// Console.WriteLine(response);
}
}
Notice that I used "async" and "await" keywords. If you are not familiar with calling an async function, you can change the "await" line to this temporarily:
var response = await client.PostAsJsonAsync("/censored/Service.svc/Login", l).Result;
This results in a 400 Bad Request with this message.
{"ErrorMessage":"Die Anmeldedaten sind ungültig.","StackTrace":null}
Which Google tells me means that the credentials are wrong. I assume that is the response one would expect with this user/password combination.
I am trying to simulate a post request using WebClient; However, When logging in using Firefox and debugging the request with firebug i find that after the POST request it automatically do some GET requests while using my code only do the POST request
MY CODE
//Handler is an overridden WebClient Class
private async Task<byte[]> Post(string uri, string[] data)
{
var postData = new NameValueCollection();
foreach (var info in data.Select(var => var.Split('=')))
{
postData.Add(info[0], info[1]);
}
return await Handler.UploadValuesTaskAsync(new Uri(uri), postData);
}
I know this isn't what you are asking for, AND its in VB, but hopefully it can help to point you in the right direction. It is what I use to make post requests on one of our websites. It works for simulating the POST data, hopefully you can incorporate some of that into what you are doing.
Dim postData As String = String.Format("RedirectLocation=RequestMethod=&username={0}&password={1}", _username, _password)
Dim _loginRequest As HttpWebRequest = WebRequest.Create(loginurl)
With _loginRequest
.Method = "POST"
.ContentLength = postData.Length
.ContentType = "application/x-www-form-urlencoded"
.KeepAlive = True
.AllowAutoRedirect = False
.CookieContainer = New CookieContainer
Using writer As New StreamWriter(.GetRequestStream)
writer.Write(postData)
End Using
.Timeout = tsTimeOut.TotalMilliseconds
_loginResponse = .GetResponse()
End With