i have few application attached to new relic. when i enter my api key and hit SEND REQUEST i get my response in json format.
curl -X GET 'https://api.newrelic.com/v2/applications.json' \
-H 'X-Api-Key:<api key>' -i
this is what the request goes. i dont know what the above code is. well i need to read the returned json message in C# and may be then deserialize the json message.
i tried this
public ActionResult Index()
{
WebRequest wr = WebRequest.Create("https://api.newrelic.com/v2/applications.json");
wr.ContentType = "application/json";
wr.Method = "GET";
//wr.Headers["X-Parse-REST-API-Key"] = "<my api key>";
wr.Headers.Add("Authorization", "<my api key>");
using (WebResponse response = wr.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
int x = 10;
}
}
but i get 500 error.
Your code is very close to working. You just need to change your request header a bit as shown below (and substitute your own api key). Then, as you say you will need to deserialize the json. I've tested this bit of code and it returned the equivalent of the curl command.
WebRequest wr = WebRequest.Create("https://api.newrelic.com/v2/applications.json");
wr.ContentType = "application/json";
wr.Method = "GET";
wr.Headers.Add("X-Api-Key:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
using (WebResponse response = wr.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
byte[] bytes = new Byte[10000];
int n = stream.Read(bytes, 0, 9999);
string s = System.Text.Encoding.ASCII.GetString(bytes);
}
}
As you probably know, you can use our api explorer to form the http request needed to extract the data you are interested in. Then you should be able to copy the request from api explorer to your c# code. See the api explorer docs here: https://docs.newrelic.com/docs/features/getting-started-with-new-relics-api-explorer.
Related
I have to send a file since a cURL command :
curl -X POST -F "csv[file]=#/mypath.csv" https://mylogin:mypassword#the-server.net
Si i tried with an HttpClient :
var client = new HttpClient();
// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("csv[file]", $#"#/{this.pathFile}")});
// Get the response.
HttpResponseMessage response = await client.PostAsync($#"https://{this.login}:{this.password}#myserver.net",requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
var testResult= await reader.ReadToEndAsync();
}
Or with the following code :
WebRequest request = WebRequest.Create($#"https://{this.login}:{this.password}#myserver.net");
// Set the Network credentials
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = $#"csv[file]=#/{this.pathFile}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response2 = request.GetResponse())
{
// Display the status.
Console.WriteLine(((HttpWebResponse)response2).StatusDescription);
// Get the stream containing content returned by the server.
using (StreamReader reader = new StreamReader(response2.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
But each time, it's the result 401 Unauthorized. Of course, my credentials are the good ones...
[EDIT]
I work for a professional project. the server where to send the file belongs to a partner. The cURL command is imposed on me and i haven't got control of this server
[EDIT 2]
I did an analysis with wireshark
IP 229 is the partners server
IP 160 is my compuer
I just have an encrypted alert. I tested with HTTP and not https but i have the same message
It Looks like that the file you are accessing is placed at a point where the user did not have any right to access the file, Try to give permission to the folder of read and write access to use the file.
That could solve your issue.
I've been working on the Walmart API but I keep getting either the 401 error or the 500 error when I run the code
public void post()
{
byte[] data = Encoding.ASCII.GetBytes(
$"username={user}&password={password}");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://marketplace.walmartapis.com/v2/feeds?feedType=item");
request.Method = "POST";
request.Accept = "application/xml;";
request.ContentLength = data.Length;
request.Headers.Add("WM_SVC.NAME", "Walmart Marketplace");
request.Headers.Add(authId);
request.Headers.Add("WM_CONSUMER.ID", user);
request.Headers.Add( time);
request.Headers.Add(CorId);
using (Stream stream = request.GetRequestStream ())
{
stream.Write(data , 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
MessageBox.Show(responseContent);
}
where authID is a signature generated from a jar file provided by walmart
time is also generated from the jar file
CorID is a randomly generated number
and user is the user id.
here is the link that describes the header parameters. Did I miss something in my header?
https://developer.walmartapis.com/#getting-started
There are multiple problems with your request. First, you are submitting a feed, but sending it as an application/xml when it should be a multipart/form-data request. Beyond this, your headers aren't set up properly and there is currently a major problem with submitting multipart/form-data requests to Walmart using C#. I have not seen a post from anyone successfully sending a feed to Walmart via C#. I am currently using C# to execute a batch file that then fires a modified version of the Walmart Java SDK which is capable of sending the multipart/form-data requests.
The reponse below is for any request other than feeds. I would start with the example listed below to get familiar with how you need to set your headers up. This is going to work for the majority of Walmart interfacing, but if the request is a feed style request, you will either need to come up with a better solution to the multipart/form-data issue, use the Java SDK, or wait for the C# SDK. If someone reads this and has a better answer as to how to submit feeds via C# exclusively I would love to hear about it!
Here is an example of an application/xml request that works.
string timestamp = CurrentTimeMillis().ToString().Trim();
string query = #"orders/"+poID+"/acknowledge";
string request = v3BaseUrl + query; //Constructed URI
string stringToSign = consumerId + "\n" +
request.Trim() + "\n" +
"POST" + "\n" +
timestamp + "\n";
string signedString = signData(stringToSign); //Your signed string
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);
webRequest.Accept = "application/xml";
webRequest.ContentType = "application/xml";
webRequest.Method = "POST";
webRequest.Headers.Add("WM_SVC.NAME", "Walmart Marketplace");
webRequest.Headers.Add("WM_SEC.AUTH_SIGNATURE", signedString);
webRequest.Headers.Add("WM_CONSUMER.ID", consumerId);
webRequest.Headers.Add("WM_SEC.TIMESTAMP", timestamp.ToString().Trim());
webRequest.Headers.Add("WM_QOS.CORRELATION_ID", Guid.NewGuid().ToString());
webRequest.Headers.Add("WM_CONSUMER.CHANNEL.TYPE", channelType);
webRequest.ContentLength = 0;
webRequest.Timeout = Timeout.Infinite;
webRequest.KeepAlive = true;
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
success = true;
}
}
I'm trying to convert cURL to C# web-request equivalent. I'm able to convert cURL to C# without response download from cURL (-o response.zip). But only problem I have is, I have no idea in c# code to translate/convert the cURL code for (-o response.zip) response.zip download file cURL syntax.
Below is my cURL.
curl -X GET -H "Content-Type: application/json" -H "X-API-TOKEN: 123456789asdfghj1234qqwerewrty" "https://yourdatacenterid.test.com/API/v3/responseexports/ES_1234sdfasas13wer/file" -o response.zip
Below is the code so far I have,
string baseURLWithResponseID = "https://yourdatacenterid.test.com/API/v3/responseexports/ES_1234sdfasas13wer/file";
var request = (HttpWebRequest)WebRequest.Create(new Uri(baseURLWithResponseID));
request.Method = "GET";
request.AllowAutoRedirect = false;
request.ContentType = "application/json";
request.Accept = "*/*";
request.Headers.Add("X-API-TOKEN", "123456789asdfghj1234qqwerewrty");
// Here I'm missing how to convert -o response.zip as C# code ?
var response = request.GetResponse();
using (var streamReader = new StreamReader(stream: response.GetResponseStream()))
{
var jsonresult = streamReader.ReadToEnd();
Response.Write(jsonresult.ToString()); //I'm able to print the response json as a string but I want it to be downloaded as a zip file
}
I got below as result from the string print which is not in a format.
Please help me to get the API response as json downloadable file in C# from cURL syntax. Thank you.
Update 1:
I have modified code as below.
string baseURLWithResponseID = "https://yourdatacenterid.test.com/API/v3/responseexports/ES_1234sdfasas13wer/file";
string path = "c:\\API_Test\\response.json";
var request2 = (HttpWebRequest)WebRequest.Create(new Uri(baseURLWithResponseID));
request2.Method = "GET";
request2.AllowAutoRedirect = false;
request2.ContentType = "application/json"; // Tried with "application/gzip" but output no change
request2.Accept = "*/*";
request2.Headers.Add("X-API-TOKEN", "123456789asdfghj1234qqwerewrty");
request2.Headers.Add("Accept-Encoding", "gzip,deflate"); // I added this new line
var responseFile = request2.GetResponse();
using (var src = responseFile.GetResponseStream())
{
using (var dst = File.Create(path))
{
src.CopyTo(dst);
}
}
Here is the output Json file, I'm not sure still in Json file is also getting non readable format. if I try same from post man application I got it as a zip file and if I unzip that I could able to read a clean json file.
Here is the image from API trial version from third party website. Please check my cURL conversion to c#, Am I missing anything ?
That's not JSON, it's the zip file's content, so you just need to read the stream binarily and write the data to a file.
.net also offers a very easy way to do this, Stream.CopyTo, just copy the response stream to a file stream and you're done:
string baseURLWithResponseID = "https://yourdatacenterid.test.com/API/v3/responseexports/ES_1234sdfasas13wer/file";
var request = (HttpWebRequest)WebRequest.Create(new Uri(baseURLWithResponseID));
request.Method = "GET";
request.AllowAutoRedirect = false;
request.ContentType = "application/json";
request.Accept = "*/*";
request.Headers.Add("X-API-TOKEN", "123456789asdfghj1234qqwerewrty");
var response = request.GetResponse();
using (var src = response.GetResponseStream())
{
using (var dst = File.Create("Path to wherever you want to store the file"))
{
src.CopyTo(dst);
}
}
You can use built-in AutomaticDecompression property of HttpWebRequest. Just add the following line after creating request:
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
I can't insert permission to a file with this code:
string URI = String.Format("https://www.googleapis.com/drive/v2/files/{0}/permissions&access_token={1}", fileId, "token");
var request = (HttpWebRequest)HttpWebRequest.Create(URI);
request.Method = "POST";
request.ContentType = "application/json";
string json = "{\"role\": \"reader\",\"type\": \"anyone\"}";
byte[] byteData = new System.Text.ASCIIEncoding().GetBytes(json);
request.ContentLength = byteData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(byteData, 0, byteData.Length);
}
var response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
json = reader.ReadToEnd();
}
I al getting a 404 error. What's the problem?
string URI = String.Format("https://www.googleapis.com/drive/v2/files/{0}/permissions&access_token={1}", fileId, "token");
Access token is not a string "token" it must be a valid access token for the user who owns the file.
Update:
permissions?access_token={1}",
You should be using ? and not & to add a parameter to the url. Not even sure you can do it like that with a HTTP Post.
Added info:
If this is not simply a typo on your part you may want to read up on Authorization a little
I also recommend checking out the Google client library instead of writing this yourself. Google.Apis.Drive.v2 Client Library.
There is a newer version of the Google Drive API you might also be interested in looking at rather then writing new code for an older version of the API. Google Drive API v3.
This may be a pathetically simple problem, but I cannot seem to format the post webrequest/response to get data from the Wikipedia API. I have posted my code below if anyone can help me see my problem.
string pgTitle = txtPageTitle.Text;
Uri address = new Uri("http://en.wikipedia.org/w/api.php");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string action = "query";
string query = pgTitle;
StringBuilder data = new StringBuilder();
data.Append("action=" + HttpUtility.UrlEncode(action));
data.Append("&query=" + HttpUtility.UrlEncode(query));
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream.
StreamReader reader = new StreamReader(response.GetResponseStream());
divWikiData.InnerText = reader.ReadToEnd();
}
You might want to try a GET request first because it's a little simpler (you will only need to POST for wikipedia login). For example, try to simulate this request:
http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page
Here's the code:
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page");
using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse())
{
string ResponseText;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
ResponseText = reader.ReadToEnd();
}
}
Edit: The other problem he was experiencing on the POST request was, The exception is : The remote server returned an error: (417) Expectation failed. It can be solved by setting:
System.Net.ServicePointManager.Expect100Continue = false;
(This is from: HTTP POST Returns Error: 417 "Expectation Failed.")
I'm currently in the final stages of implementing an C# MediaWiki API which allows the easy scripting of most MediaWiki viewing and editing actions.
The main API is here: http://o2platform.googlecode.com/svn/trunk/O2%20-%20All%20Active%20Projects/O2_XRules_Database/_Rules/APIs/OwaspAPI.cs and here is an example of the API in use:
var wiki = new O2MediaWikiAPI("http://www.o2platform.com/api.php");
wiki.login(userName, password);
var page = "Test"; // "Main_Page";
wiki.editPage(page,"Test content2");
var rawWikiText = wiki.raw(page);
var htmlText = wiki.html(page);
return rawWikiText.line().line() + htmlText;
You seem to be pushing the input data on HTTP POST, but it seems you should use HTTP GET.
From the MediaWiki API docs:
The API takes its input through
parameters in the query string. Every
module (and every action=query
submodule) has its own set of
parameters, which is listed in the
documentation and in action=help, and
can be retrieved through
action=paraminfo.
http://www.mediawiki.org/wiki/API:Data_formats