this is my code
Uri uri = new Uri(this.Url);
var data = client.DownloadData(uri);
if (!String.IsNullOrEmpty(client.ResponseHeaders["Content-Disposition"]))
{
FileName = client.ResponseHeaders["Content-Disposition"].Substring(client.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 10).Replace("\"", "");
}
how to get the file name without download the file, I mean without using client.DownloadData??
WebClient will not support it but with HttpWebRequest you can either try to be nice and send a HEAD request if the server supports it or if it doesn't send a normal GET request and just don't download the data:
The HEAD request:
HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(uri);
request.Method = "HEAD";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
string disposition = response.Headers["Content-Disposition"];
string filename = disposition.Substring(disposition.IndexOf("filename=") + 10).Replace("\"", "");
response.close();
If the server doesn't support HEAD, send a normal GET request:
HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
string disposition = response.Headers["Content-Disposition"];
string filename = disposition.Substring(disposition.IndexOf("filename=") + 9).Replace("\"", "");
response.close();
Related
Hey im trying to post an http request (Create Teams online meeting) to the Graph API under c# .Net Framework 4.0 so i cannot use the Graph-SDK and i cannot use the System.net.http libary (no httpClient). I tried HttpWebRequest but im having difficulties with posting Json to the API.
My Request Function looks like this:
private string SendHttpRequest(string Method, string ContentType, WebHeaderCollection Headers, string Content, string URI)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
request.Method = Method;
request.Headers = Headers;
request.PreAuthenticate = true;
request.ContentType = ContentType;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write(Content);
requestWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseText = responseReader.ReadToEnd();
responseReader.Close();
return responseText;
}
catch (Exception ex)
{
throw (ex);
}
}
And this works fine when my Content Type is text/xml(for a diffrent API) but not if its Application/Json.
I always get an Error 400 when i call HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Method = "POST"
ContentType = "application/json"
Headers = Headers.Set(HttpRequestHeader.Authorization, "Bearer " + accessToken);
Content = string jsonContent = JsonConvert.SerializeObject(Content);
URI = "https://graph.microsoft.com/v1.0/me/onlineMeetings"
for anyone with the same difficulties.
I was missing the Timezones in my startDateTime and endDateTime.
To add those i had to Format my DateTime i recive from my database.
This worked for me:
TimeAndOffset = new DateTimeOffset(reservation.beginnUhrzeit,
TimeZoneInfo.Local.GetUtcOffset(reservation.beginnUhrzeit));
teamsCreate.startDateTime = TimeAndOffset.ToString("o");
reservation.beginnUhrzeit is my Database variable
teamsCreate is an Object i can later serialize to Json
After that everything worked.
I want to make Post request to "https://sslecal2.forexprostools.com/ajax.php". So there is my code:
string URI = "https://sslecal2.forexprostools.com/ajax.php";
string requestBody = String.Format("{{\"dateFrom\": \"{0}\", \"dateTo\": \"{1}\", \"timeZone\": {2}, \"action\": \"{3}\"}}",
"2018-12-24", "2018-12-24", 18, "filter"); //json format
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI); //make request
request.Method = "POST";
request.UserAgent = "";
request.Headers.Add("X-Requested-With", "XMLHttpRequest");
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(requestBody); //write your request payload
}
WebResponse response = request.GetResponse();
string jsonData = String.Empty;
using (var reader = new StreamReader(response.GetResponseStream()))
{
jsonData = reader.ReadToEnd();
}
response.Close();
I made something not correct in "requestBody" in string " string requestBody = String.Format("{{\"dateFrom\"..." because I get 200 and empty html answer.
And I attach the screens of the same request in postman with html code in answer. This request in postman processes well.
What the difference between this Post webrequest and request in Postman?
With postman you posting different format data. To get same thing in code you need to change request body format and set content type of request:
string URI = "https://sslecal2.forexprostools.com/ajax.php";
string requestBody = String.Format("dateFrom={0}&dateTo={1}&timeZone={2}&action={3}",
"2018-12-24", "2018-12-24", 18, "filter"); //<-- Change this
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI);
request.Method = "POST";
request.UserAgent = "";
request.Headers.Add("X-Requested-With", "XMLHttpRequest");
request.ContentType = "application/x-www-form-urlencoded"; //<-- Add this
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(requestBody);
}
WebResponse response = request.GetResponse();
string jsonData = String.Empty;
using (var reader = new StreamReader(response.GetResponseStream()))
{
jsonData = reader.ReadToEnd();
}
response.Close();
In PostMan, if you click the "Code" in the top right, under the send button, you can choose C# (RestSharp).. If you're not using RestSharp, there's a small amount of work to do to convert it to something else, but the basics are all there.
Here's the autogen output for your case (RestSharp):
var client = new RestClient("https://sslecal2.forexprostools.com/ajax.php");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "bfd1a3b3-983f-4160-a091-6f0962413e58");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("X-Requested-With", "XMLHttpRequest");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("undefined", "dateFrom=2018-01-24&dateTo=2018-01-24&timeZone=18&action=filter", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Converting it to HttpWebRequest requires:
AddHeader -> Headers.Add
Specify method
Body data is set differently - take PostMan's string and write it to the request stream
Or install RestSharp free from NuGet
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();
curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/AC053acaaf55d75ef32233132196e/Messages.json' \
--data-urlencode 'To=5555555555' \
--data-urlencode 'From=+15555555555' \
--data-urlencode 'Body=Test' \
-u AC053acaaf55d75a393498192382196e:[AuthToken]
I have the above curl code for an API I need to connect to. The problem is I need to connect using ASP.NET (C#). I'm not very familiar with ASP.NET and don't really know where to begin. I know how to code this in PHP but ASP.NET is another matter. From the research I've done I need to use WebRequest. How do I feed in the post data and the authtoken (-u AC053acaaf55d75a393498192382196e:[AuthToken]) part of the request.
string url = "https://api.twilio.com/2010-04-01/Accounts/AC053acaaf55d75ef32233132196e/Messages.json";
WebRequest myReq = WebRequest.Create(url);
myReq.Method = "POST";
Twilio evangelist here.
Just to make sure we are on the same page, you need to make a POST request to theMessages endpoint in the Twilio API, but you cannot use our helper library.
Not a problem, you can just use .NETs native HTTP client libraries, HttpWebRequest and HttpWebResponse. Thats going to look something like this:
//Twilio Credentials
string accountsid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string authtoken = "asdsadasdasdasdasdsadsaads";
//Twilio API url, putting your AccountSid in the URL
string urltemplate = "https://api.twilio.com/2010-04-01/Accounts/{0}/Messages.json";
string url = string.Format(urltemplate, accountsid);
//Create a basic authorization
string basicauthtoken = string.Format("Basic {0}", System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(accountsid + ":" + authtoken)));
//Build and format the HTTP POST data
string formencodeddata = "To=+15555555555&From=+15556666666&Body=Hello World";
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(formencodeddata);
//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.CreateHttp(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.Headers.Add("Authorization", basicauthtoken);
using (Stream postStream = webrequest.GetRequestStream()) {
postStream.Write(formbytes, 0, formbytes.Length);
}
//Make the request, get a response and pull the data out of the response stream
var webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
var reader = new StreamReader(responseStream);
string result = reader.ReadToEnd();
There are also async versions of the GetRequestStream and GetResponse methods if you need them.
Hope that helps.
Twilio has some great docs for this here: http://www.twilio.com/docs/api/rest/making-calls
they also have a great c# library here; twilio.com/docs/csharp/install but here's an example in C# showing how to make a call.
using System;
using Twilio;
class Example {
static void Main(string[] args) {
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "AC3094732a3c49700934481addd5ce1659";
string AuthToken = "{{ auth_token }}";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var options = new CallOptions();
options.Url = "http://demo.twilio.com/docs/voice.xml";
options.To = "+14155551212";
options.From = "+14158675309";
var call = twilio.InitiateOutboundCall(options);
Console.WriteLine(call.Sid);
}
}
Working code for me
string accountsid = "AccountSid";
string authtoken = "AuthToken";
//Twilio API url, putting your AccountSid in the URL
string urltemplate = "https://api.twilio.com/2010-04-01/Accounts/{0}/Messages.json";
string url = string.Format(urltemplate, accountsid);
//Get Client Secret and client key from the API Keys section-- https://www.twilio.com/docs/iam/keys/api
string basicauthtoken = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("ClientSecret:ClientKey"));
//Build and format the HTTP POST data
string formencodeddata = "To={To}&From={From}&Body={Body}";
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(formencodeddata);
//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.CreateHttp(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.Headers.Add("Authorization", basicauthtoken);
using (Stream postStream = webrequest.GetRequestStream())
{
postStream.Write(formbytes, 0, formbytes.Length);
}
//Make the request, get a response and pull the data out of the response stream
var webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
var reader = new StreamReader(responseStream);
string result = reader.ReadToEnd();
I am using Innovative Text SMS API gateway which is through me error.
Documentation is available at link http://www.innovativetxt.com/services/sms_api_gateway.htm, the error is happening on my local machine, but works fine at the production server.
The remote server returned an error: (405) Method Not Allowed.
at this line of code:
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
try
{
// InnovativeTXT POST URL
string url = "http://innovativetxt.com/cp/api";
// XML-formatted data
string toSender = "4477878585244";
string fromSender = "Test";
string textMessage = "Thanks for Choosing Innovative Text Messaging Solution.";
string fields = "?to=" + toSender + "&from=" + fromSender + "&text=" + textMessage + "&api_key=xxx&api_secret=xxxxx";
url = url + fields;
// web request start
Uri uri = new Uri(url);
string data = "field-keywords=ASP.NET 2.0";
if (uri.Scheme == Uri.UriSchemeHttp)
{
// create a request on behalf of uri
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
// setting parameter for the request
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
// a stream writer for the request
StreamWriter writer = new StreamWriter(request.GetRequestStream());
// write down the date
writer.Write(data);
//close the stream writer
writer.Close();
// getting response from the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);
// to write a http response from the characters
Response.Write(readStream.ReadToEnd());
// close the response
response.Close();
// close the reader
readStream.Close();
}
}
catch (Exception exp)
{
// catch for unhelded exception
Response.Write(exp.Message);
}
This issue relates to IIS Handler mappings.
You should specify the file name at the end of string URL:
string url = "http://innovativetxt.com/cp/api/somepage.aspx";
You can use default pages like, default.aspx or index.php etc...