I used the top answer from HTTP request with post
however an error pops up in visual studio saying 404 remote server not found.
The website exists, it is a rails app bounded to the ip address of my router.
Using the following url in the browser updates the attribute of the applicant entity in the rails app. However using the c# app to do this is not working.
http://<ADDRESS HERE>:3000/api/v1/applicants/update?id=2&door=true
I have the ff:
using System.IO;
using System.Net;
using System.Text;
I used the following code inside a btn click
private void button1_Click (object sender, EventArgs e){
var request = (HttpWebRequest)WebRequest.Create("http://<ADDRESS HERE>:3000/api/v1/applicants/update");
var postData = "id=2";
postData += "&door=true";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
Are you sure you need to perform a POST request and not a GET request? I'm asking, because there seems to be inconsistency in your question. First you say you want to get to the url
http://<ADDRESS HERE>:3000/api/v1/applicants/update?id=2&door=true
which is a url with querystring params, but in the code you separate the querystring and send the params as POST data.
The GET request would look something like this
GET http://<ADDRESS HERE>:3000/api/v1/applicants/update?id=2&door=true HTTP/1.1
Host: <ADDRESS HERE>
... (more headers)
And the POST request:
POST http://<ADDRESS HERE>:3000/api/v1/applicants/update HTTP/1.1
Host: <ADDRESS HERE>
Content-type: application/x-www-form-urlencoded
... (more headers)
id=2&door=true
Related
I need to replicate a HTTP request using C# and the HttpWebRequest, that looks like this:
HEADER: POST /upnp/control/x_contact HTTP/1.1 Host: fritz.box:49000
Connection: Keep-Alive User-Agent:...
So far I got everything working, except for the part after the POST
"/upnp/control/x_contact HTTP/1.1".
How would I have to modify the HttpWebRequest to get these additional data to the server?
PS: This is how the java code looks, that generates the correct request. I would like to port this code to C# and send the same request from there:
socket = new Socket(InetAddress.getByName("fritz.box"), 49000);
// Send header
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
writer.write("POST /igdupnp/control/WANIPConn1 HTTP/1.1");
writer.write("Host: fritz.box:49000\r\n");
writer.write("SOAPACTION: \"urn:schemas-upnp-org:service:WANIPConnection:1#GetStatusInfo\"\r\n");
writer.write("Content-Type: text/xml; charset=\"utf-8\""+"\r\n");
writer.write("Content-Length: " + myData.length() + "\r\n");
writer.write("\r\n");
// Send data
writer.write(myData);
writer.flush();
And this is my C# code so far (producing an incomplete HTML request):
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (#"http://fritz.box:49000");
webRequest.Headers.Add ("SOAPACTION", "urn:schemas-upnp-org:service:WANIPConnection:1#GetStatusInfo");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
I am facing the following issue while issuing request to retrieve the access token. First, I registered the application in developer console and consequently downloaded the client secret file. The content of which is as below: (i have marked secrets as xxxxx).
{"installed":{"client_id":"xxxx","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"xxxx","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
In the developer documentation (located at : https://developers.google.com/identity/protocols/OAuth2InstalledApp ) however, it is given a different address to connect and retrieve the access tokens.
POST /oauth2/v3/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
I am confused
1. which URI's to use to get access to tokens.
2. What redirect_uri should be used? Is it the local host or the uri as noted in the developer documentation.
When i use the client secret token uri, i receive a 400 bad request and when i use the uri as noted in the developer documentation, I receive forbidden 403.
POST /oauth2/v3/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
Can someone kindly clarify. It would be an immense help.
I am writing a console application and i do not want to use the C# api already provided. The sample code is located below.
Where am I doing wrong?
string tokenUri = #"https://accounts.google.com/o/oauth2/token";
HttpWebRequest request=(HttpWebRequest) WebRequest.Create(tokenUri);
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("code", this.clientCode);
outgoingQueryString.Add("client_id", this.clientID);
outgoingQueryString.Add("client_secret", this.clientSecret);
outgoingQueryString.Add("redirect_uri", "https://oauth2-login-demo.appspot.com/code");
outgoingQueryString.Add("grant_type","authorization_code");
string postdata = outgoingQueryString.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream reqStr = request.GetRequestStream();
reqStr.Write(byteArray, 0, byteArray.Length);
reqStr.Flush();
reqStr.Close();
HttpWebResponse response=request.GetResponse() as HttpWebResponse;
Console.WriteLine(response.StatusCode.ToString());
Found out that url-encoded is not to be used, instead json is expected. revised the code as below and still 400 persist.
string tokenUri = "https://accounts.google.com/o/oauth2/token";
TokenFileds f = new TokenFileds() { client_code = this.clientCode, client_id = this.clientID, client_secret = this.clientSecret, redirect_uri = "urn:ietf:wg:oauth:2.0:oob", grant_type = "authorization_code" };
//string retString=this.SerializeToJson<TokenFileds>(f);
string retString = this.NewjsonLib(f);
byte[] byteArray=Encoding.UTF8.GetBytes(retString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(tokenUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
request.ContentLength = byteArray.Length;
Stream strm = request.GetRequestStream();
strm.Write(byteArray, 0, byteArray.Length);
strm.Flush();
strm.Close();
HttpWebResponse response =request.GetResponse() as HttpWebResponse;
you need to insure few things before as,
1. While creating the project you have to select other type project.
2. You must enable the drive API's.
3. Then make sure you are posting this url L"/o/oauth2/token" to this server L"accounts.google.com".
4. you are giving Content Type as L"Content-Type: application/x-www-form-urlencoded".
5.and your header should be like this,
wstring wstrHeader = L"code="+ m_wstrAuthCode +
L"&client_id=327293200239-4n4a8ej3jlm1fdufqu7httclg5a28m1a.apps.googleusercontent.com&client_secret=ieEGhWhPhotp0ZegdgRLkOxv&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code";
here you have to replace m_wstrAuthCode to your authentication code.
6.then you will get the Json from server as,
{
"access_token" : "ya29.7gGjEgvIVIMOO7bHegijk2KygAVjjxz7bCOxUvG7OKeKTc66Nom1e9zCqSyzR4V0bTYC",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/Vc9A7nfib4ikeYs0-TBfrs-isvjRDt-JI2ftj0pNVcRIgOrJDtdun6zK6XiATCKT"
}
7.you need to parse it to get the access token.
I'm trying to send requests and get responses from MailChimp API . . so far, GET, POST and DELETE are working good however, PATCH always results to Bad Request can you identify the error in this code?
string data = "{\"name\": \"TestListTWOTWOTWO\"}";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Headers[HttpRequestHeader.Authorization] = accessToken;
request.Method = "PATCH";
request.ContentType = "text/plain;charset=utf-8";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
// Send the data.
requestStream.Write(bytes, 0, bytes.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
the error occus on the line with request.GetResponse();
it is an unhandled WebException saying The remote server returned an error: (400) Bad Request
after checking the error response, here's the what it says
"Your request doesn't appear to be valid JSON:
\nParse error on line 1:\nPATCH /3.0/lists/9bb\n^\n
Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['"
Many C# libraries seem to try to use the Expect: 100-Continue header, which MailChimp/Akamai has a problem with when combined with PATCH. You have two options.
Turn off Expect: 100-Continue in your HTTP library. In one C# library, you do that with a line of code like Client.DefaultRequestHeaders.ExpectContinue = False
Tunnel the PATCH request through HTTP POST using the X-Http-Method-Override header. Here's more details on that header.
Cause PATCH is a quite new RFC, so you would not expect that more then a few services support it at all. You'd better check that if the service supports it.
You send request using json format, but set content type to "text/plain" is that OK?
I'm Getting HTTP 500 error when calling following REST via c#, but I was able to do the POST by using chrome REST Console
Request body sent ( Got from REST console)
Request Url: http://dev-6666.amazonaws.com/CourseEnrollment
Request Method: POST
Status Code: 201
Params: {
"MESSAGE-TYPE": "UserEnrollmentCreate",
"PAYLOAD": "<userstd version=\"\"\"\"><user password=\"\"PSEUDO-5621b55a\"\" lastname=\"\"Wara\"\" emailaddress=\"\"student3#bloody.com\"\" loginid=\"\"BloodyStudent3\"\" firstname=\"\"Buddihi\"\" userid=\"\"19658121\"\" clientid=\"\"117112\"\" createdate=\"\"2014-04-29T03:55:54.873\"\" lastupdate=\"\"2014-05-29T03:55:54.873\"\"><userproperty propertyname=\"\"\"\" propertyvalue=\"\"\"\" createdate=\"\"\"\" lastupdate=\"\"\"\"></userproperty></user></userstd>"
}
C# method used (This is the one getting 500 error)
private void TestCreateUser()
{
string requestData = "{\"MESSAGE-TYPE\":UserEnrollmentCreate,\"PAYLOAD\":\"<userstd version=\"\"\"\"><user password=\"\"PSEUDO-5621b55a\"\" lastname=\"\"Wara\"\" emailaddress=\"\"student3#bloody.com\"\" loginid=\"\"BloodyStudent3\"\" firstname=\"\"Buddihi\"\" userid=\"\"19658121\"\" clientid=\"\"117112\"\" createdate=\"\"2014-04-29T03:55:54.873\"\" lastupdate=\"\"2014-05-29T03:55:54.873\"\"><userproperty propertyname=\"\"\"\" propertyvalue=\"\"\"\" createdate=\"\"\"\" lastupdate=\"\"\"\"></userproperty></user></userstd>}";
byte[] data = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dev-6666.amazonaws.com/CourseEnrollment");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
form-url-encoded data should be in form (variablename)=(data)&(variablename)=(data)....
The console representation is a bit messy, so the real data string should be
string requestData = "MESSAGE-TYPE=UserEnrollmentCreate&PAYLOAD=<userstd version=\"\"\"\"><user password=\"\"PSEUDO-5621b55a\"\" lastname=\"\"Wara\"\" emailaddress=\"\"student3#bloody.com\"\" loginid=\"\"BloodyStudent3\"\" firstname=\"\"Buddihi\"\" userid=\"\"19658121\"\" clientid=\"\"117112\"\" createdate=\"\"2014-04-29T03:55:54.873\"\" lastupdate=\"\"2014-05-29T03:55:54.873\"\"><userproperty propertyname=\"\"\"\" propertyvalue=\"\"\"\" createdate=\"\"\"\" lastupdate=\"\"\"\"></userproperty></user></userstd>";
The response should have been 400 in a working implementation as you specify application/x-www-form-urlencoded while you post application/json as content.
WebApi probably returns 500 as it tried to decode the content as a form while the content actually is JSON, hence it get's an exception and therefore return 500 as status code.
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.