URI Update Request - c#

From my C# console application, I want to issue an Uri update request. Like the following:
http://username:password#dynupdate.no-ip.com/nic/update?hostname=mytest.testdomain.com&myip=1.2.3.4
I have tried the following:
string url = "http://username:password#dynupdate.no-ip.com/nic/update? hostname=mytest.testdomain.com&myip=1.2.3.4";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 5000;
But, I am getting, Invalid URI: The format of the URI could not be determined. error.
Any idea, where I went wrong? I type the full url as shown above into a web browser and it works as expected but through the C# application, it throws an exception.
Is there any other way to implement this?

You need to create and add some credentials to the request and then access the URI without passing in the username/password.
For more information : How to: Request Data Using the WebRequest Class (Specifically the section regarding credentials)
For example;
var uri = new Uri("http://somesite.com/something");
var request = WebRequest.Create(uri) as HttpWebRequest;
request.Credentials = new NetworkCredential("myUserName","myPassword");
request.PreAuthenticate = true;

Just have look at this web page. Is this what you are referring to?
http://www.no-ip.com/integrate/request/
I think you need to use the url as
http://dynupdate.no-ip.com/nic/update
and then send the credentials as mentioned by ChrisBint. And you need to set the preference to base64 ...if there is a provision for that
+ some headers like UserAgent as mentioned in the article.

Encode the URL argument, check the below example
string url = "http://www.stackoverflow.com?question=" + HttpUtility.UrlEncode("a sentence with spaces");
WebRequest r = WebRequest.Create(url);

Related

Cannot access azure storage table using SAS via c#. Works in postman and browser

I am trying to obtain and parse a table from azure storage.
I generated a Shared Access Signature in azure storage explorer.
If I paste the generated url into browser or postman I get the table back as xml.
However, trying to do a HttpWebRequest with the url results in
System.Net.WebException: 'The remote server returned an error: (415) Unsupported Media Type.'
I have tried different content and accept types
const string url = #"https://laptopdeploymentfiles.table.core.windows.net/PaulLoginScript?st=2019-08-21T08%3A10%3A22Z&se=2019-08-22T08%3A10%3A22Z&sp=r&sv=2018-03-28&tn=paulloginscript&sig=***";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
var webResponse = request.GetResponse();
I have tried both
request.Accept = "application/xml";
and
request.ContentType = "application/xml";
but still get the same error.
I have also tried creating and accessing a new table with only simple data. The data accessed via the brower is valid xml, but I still get the same error from a c# app.
The solution was to use both the following contenttype and accept formats
request.Accept = "application/json";
request.ContentType = "application/json";
The solution was to use both the following contenttype and accept formats
request.Accept = "application/json";
request.ContentType = "application/json";
Tested your specific scenario and got it working by using the HttpClient class.
Here's the code I used to get it working:
// Create an instance of HttpClient with the BaseAddress
var client = new HttpClient
{
BaseAddress = new Uri("https://<STORAGE_NAME>.table.core.windows.net/")
};
// Add an Accept Header to tell the service you're expecting the data in JSON format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Get the actual table
var result = await client.GetAsync("<REST_OF_THE_URI");
When omitting the Accept-header, this code gives the error message:
Atom format is not supported.
EDIT
Taken from Query Tables - Request headers about the Accept header you can specify:
Optional. Specifies the accepted content type of the response payload. Possible values are:
application/atom+xml (versions prior to 2015-12-11 only)
application/json;odata=nometadata
application/json;odata=minimalmetadata
application/json;odata=fullmetadata
I think you need to tell your request what kind of data to expect. Try adding this:
request.ContentType = "application/xml";
I've not tested, so I can't promise this will work. Let me know if it does!
EDIT:
Paul, I tested this code below:
const string url = #" -- used my own xml file in Azure Blob Storage --";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/xml";
var webResponse = request.GetResponse();
It worked with no errors. webResponse was populated just fine. I just whipped up a console app and put these 5 lines of code in it, and then stepped through in debug mode to see what would happen.
I wonder what is different about your environment? Could you try isolating these lines of code?
EDIT 2:
Just a thought... are you sure the XML in your file is valid?

Can not Access a URL using Webrequest

I am trying to get access a URL using .Net but when I run my Program I get the Error The remote server returned an error: (403) Forbidden. Now, the issue is if I click the link http://thisIsMyUR, and enter the user name and password as in the below code. It totally works. I am not able to understand why this exception is coming? Please refer the code below.
Side Note: I am using this sample function below to fire Build of my project in Jenkins Server.
string url = "http://thisIsMyURL";
WebRequest webRequest = WebRequest.Create(url);
webRequest.Credentials = new NetworkCredential("admin", "pass");
WebResponse response = webRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
Other than what was recommended by Bradley Uffner in the comments, you can try to provide an actual user agent during the request. I have seen certain servers which would not respond to requests without that header for some odd perceived security reason.
EDIT: as requested, i'll update with some more information.
Some servers may choose to ignore requests, giving some error code (or closing connection) when certain conditions are not met. A good way of checking if that is the case, is to actually send all the standard headers sent by your average web browser in the request. The "User agent" is one of those headers, and this example adds it to your request:
string url = "http://thisIsMyURL";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.UserAgent = "USER AGENT VALUE";
HttpWebRequest.Credentials = new NetworkCredential("admin", "pass");
WebResponse response = webRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
The cast to HttpWebRequest is required so you have access to the UserAgent header field. Other standard HTTP fields can be accessed this way.
You can check which headers are sent by your browser of choice by inspecting its requests using the browser developer tools (usually Right click on webpage -> Inspect elements -> Network).
I figured it out with the help of some articles. A basic authentication needs to be added. Below is a sample.
var userName = "admin;"
var password = "password";
var encodedAuthentication = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
webRequest.Headers.Add("Authorization", "Basic " + encodedAuthentication);

Get query string from a http response

If I copy and past the following URL in the browser, I get a response URL with a query string sessionid in it:
https://abc.abcdefg.com/abcd/sessionServlet
I am trying to capture that response URL and session id in my code behind in .net:
string url = "https://abc.abcdefg.com/abcd/sessionServlet";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Label1.Text = response.ResponseUri.ToString();
the response.ResponseUri contains my original URL, but not the response URL I get back from the sessionServlet.
Could anyone help me? Thank you in advance.
Looking at your comment about the http://devserver/myproject/login.aspx?sessionid=1341351j1oij4o1i3o13i5ho1i3j4134o URL appearing the browser from vising the URL https://abc.abcdefg.com/abcd/sessionServlet, you're probably being redirected using HTTP 301 or 302.
If so, I'd add request.AllowAutoRedirect = true MSDN which will allow your web request to follow that redirect. Then response.ResponseUri.Query should have the querystring that you're looking for.

Get And Use Facebook Access Token Without HTTPS

I have the following url for the first stage. getting code http://www.facebook.com/dialog/oauth?client_id=myappid&redirect_uri=myurl;state=e879888c-7090-4c09-98a5-ff361b30d55;scope=email
and
url = String.Format(#"http://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}",FacebookAppId, redirectUrl, FacebookSecret, code);
WebClient webClient = new WebClient();
var tokenVars = webClient.DownloadString(url);
var responseVars = HttpUtility.ParseQueryString(tokenVars);
string access_token = responseVars["access_token"];
string data = webClient.DownloadString(String.Format("http://graph.facebook.com/me?access_token={0}", access_token));
var jobject = JObject.Parse(data);
400 BAD REQUEST is returned.
Question: Is it possible to get facebook access token without connecting by http s ?
Question: Is it possible to use access_token without HTTPS? NOT HTTP
for a secure you must take https,
maybe if you aren't, some bad thing will show, #long process..
i just browse for your issue, and same thing

Issues retrieving facebook social plugin comments for page, C# HttpWebRequest class

I'm hoping I've done something knuckle-headed here and there is an easy answer. I'm simply trying to retrieve the list of comments for a page on my site. I use the social plug-in and then retrieve the comment id via the edge event. Server side I send the page id back and do a simple request using a HttpWebRequest. Worked well back in October, but now I get an 'internal error' response from FB. I can use the same url string put it into a browser and get the comments back in the browser in json.
StringBuilder url = new StringBuilder();
url.Append("https://graph.facebook.com/comments/?ids=" + comment.page);
string requestString = url.ToString();
HttpWebRequest request = WebRequest.Create(requestString) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Ideas? Thanks much in advance.
Since you're using the Facebook C# SDK (per your tag), try:
var url = "{your url}";
var api = new Facebook.FacebookClient(appId,appSec);
dynamic commentsObj = api.Get("/comments/?ids=" + url);
dynamic arrayOfComments = commentsObj[url].data

Categories