I have rest api url like this
https://example.com/ProductAPI/api/V1/getproduct.
This api has api_key,username and password.How can I access this api and getproduct details using c#.I tried like this
WebRequest request = WebRequest.Create(#"https://example.com/ProductAPI/api/V1/getproduct");
request.Method = "GET";
request.Headers.Add("api_key","5g13441f-6915-4a34-8a53-bcb4er88b554");
request.Headers["Authorization"] = "Basic" + Convert.ToBase64String(Encoding.Default.GetBytes("admin:123"));
request.ContentLength = 0;
request.ContentType = #"application/json; charset=utf-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
Console.WriteLine(jsonResponse);
Console.ReadLine();
}
But it show 401 unauthorized error.Pls help to solve this
Related
I am not familiar with REST webservices, but I am trying to get a response from one of them in a C# application.
I am trying to connect to the webservice and authenticate my application to get a token. For this, I have an URL, a login and a password.
When I call the authentication method with cURL tool, I get a « success :true» answer, followed with the token string.
But when I try to do the same with my C# code, I always get a « success :false» answer and no token.
Can somebody help me to understand what is missing in my C# code to get the correct answer ? Thank you.
The cURL request (given by the webservice owner) is:
curl -X POST -d "{\"user\":\"mylogin\",\"pwd\":\"mypassword\"}" \
-H "Content-Type: application/json" http://webserviceURL/authenticate
My code is the following : (restlogin, restpassword and resturl are three strings and get the correct values for the connection. The resulting string is obtained in the variable nammed token).
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resturl + "authenticate");
request.Method = "POST";
request.Credentials = new NetworkCredential(restlogin, restpassword);
request.ContentType = "application/json";
request.Timeout = 30000;
request.ReadWriteTimeout = 30000;
request.Accept = "application/json";
request.ProtocolVersion = HttpVersion.Version11;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream respStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
token = reader.ReadToEnd();
reader.Close();
reader.Dispose();
response.Close();
}
}
As per my comment to the question, you are not sending your credentials in the request body. With request.Credentials you're setting the Authentication Header in your HttpRequest.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resturl + "authenticate");
request.Method = "POST";
request.ContentType = "application/json";
request.Timeout = 30000;
request.ReadWriteTimeout = 30000;
request.Accept = "application/json";
request.ProtocolVersion = HttpVersion.Version11;
// Set your Response body
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"user\":\"" + restlogin + "\"," +
"\"pwd\":\"" + restpassword + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream respStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
token = reader.ReadToEnd();
reader.Close();
reader.Dispose();
response.Close();
}
}
Here is the code that I am using:
public static void FetchXML()
{
_url = new Uri("http://api.tumblr.com/v2/blog/" + _username + ".tumblr.com/likes?api_key=REc3Z6l4ZYss11a8lX6KKje0X8Hsi9U77SyaPbQrOBBCGJGA6D");
var client = new RestClient();
client.Authority = _url.ToString();
var request = new RestRequest();
request.AddParameter("limit", "20");
request.AddParameter("offset", _offset.ToString());
var response = client.Request(request);
var content = response.Content.ToString();
var parsedResponse = JsonParser.FromJson(content);
}
If I take the Uri value and paste it into my browser (using a valid Tumblr username) I'm getting the correct Json, but in my application the content of response is:
"{\"meta\":{\"status\":401,\"msg\":\"Unauthorized\"},\"response\":[]}"
Anyone have any idea why this is? According to the Tumblr API
retrieving likes should only need the API key, which I am providing.
Hi you can use the below code to get the response.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "Application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receive = response.GetResponseStream();
StreamReader reader = new StreamReader(receive, Encoding.UTF8);
string respond = reader.ReadToEnd();
I'am trying to use example api call in below link please check link
http://sendloop.com/help/article/api-001/getting-started
My account is "code5" so i tried 2 codes to get systemDate.
1. Code
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
2.Code
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
But i don't know that i use correctly api by above codes ?
When i use above codes i don't see any data or anything.
How can i get and post api to Sendloop.And how can i use api by using WebRequest ?
I will use api first time in .net so
any help will be appreciated.
Thanks.
It looks like you need to post your API key to the endpoint when making requests. Otherwise, you will not be authenticated and it will return an empty response.
To send a POST request, you will need to do something like this:
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx";
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
string userAuthenticationURI =
"https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ originZip +
"&destinations="+ DestinationZip + "&units=imperial&language=en-
EN&sensor=false&key=Your API Key";
if (!string.IsNullOrEmpty(userAuthenticationURI))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
var responseString = new
StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(responseString);
}
I would like to write a class in c# which should send an HTTP request (post) to a PHP file which is on my server in order to retrieve a json object.
This is the code I've got:
public void SendRequest(){
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("url");
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
}
Is that what I need? What do you think I should change or improve?
Thank you for your help.
You need to post data and read the response:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
string yourPostData = "Your post data";
string sreverResponseText;
byte[] postDataBytes = Encoding.UTF8.GetBytes(yourPostData);
request.ContentLength = yourPostData.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
using (response = (HttpWebResponse)request.GetResponse())
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
sreverResponseText = streamReader.ReadToEnd();
Now what you are looking for is in sreverResponseText, also you can access headers from response.Headers.ToString()
i used following code to get the access token from code as below
String code = HttpContext.Current.Request["code"];
string redirecturl = HttpContext.Current.Request["url"];
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = UrlEncodeForGoogle(url);
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}&access_type={5}";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
string param = string.Format(data, code,configurationInfo.oauthclientid , configurationInfo.oauthclientsecretid, redirect_uri_encode, grant_type, "offline");
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
i am getting response as
The remote server returned an error: (400) Bad Request.
i do not know where i went wrong
waiting for your valuable comments
Google also provides a higher level library for accessing its services. I find it makes it much easier to work with its APIs.
http://code.google.com/p/google-api-dotnet-client/