Sending an HTTP PUT request with a parameter in C# - c#

I have a tika server open on my PC, and I need to send it a request with a string parameter which is a path for a file I want tika to process. The code I have so far is:
private void getFromServer(string fileName)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:9998/rmeta");
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "PUT";
httpWebRequest.KeepAlive = true;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string postData = #"C:\Users\######\Downloads\elasticsearch\elasticsearch-1.7.1.zip";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
string json = postData;
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
console.write(responseText);
}
}
The thing is, the server gets the request, but it returns the string I sent it instead of the contents of the file in question, and I know it can work because I sent it the same request using a cURL command and it worked. Any ideas what I'm doing wrong?
PS the hashtags are instead of my username

Related

C#: Huggingface API - Text to Speech

I want to use a speech to text API in C# from huggingface(https://huggingface.co/facebook/fastspeech2-en-ljspeech) but I'm facing some difficulties.
I tried the following :
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api-
inference.huggingface.co/models/facebook/fastspeech2-en-ljspeech");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{'text': 'My name is Teven and I am'}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
byte[] byteArray = Encoding.UTF8.GetBytes(result); //Not sure about this line
File.WriteAllBytes(#"C:\Users\...\test.flaC", byteArray);
}
I'm not sure how to use it, I got as an output the test.flaC audio file, but it does not work. I know that C# have an internal Text2Speech API, but I want to use this one because it has better features.

Convert CURL "-i --user" to C# HttpWebRequest

I want to run a CURL POST to send SMS message via Plivo API service.
I do it by using HttpWebRequest in C# (see below).
Parametres as as follow:
POSTurl = "https://api.plivo.com/v1/Account/MA****************M2/Message/'”
JSONRequest == "src=+972545675453&dst=0545675453&text=TEST”
In their docs I need to user the following parameter:
-i --user AUTH_ID:AUTH_TOKEN
I don't know how to implement this but it not work (401 error -unauthorised)
I tried to use it instead auth parameter in my code as follow:
auth == “MA****************MM2:Yj**************************M5ZjA4"
Need some advice 😳
Thanks
This is my code:
public static SqlString POSTSG(String POSTurl, String auth, SqlString JSONRequest)
{
SqlPipe pipe = SqlContext.Pipe;
//Create Request
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(POSTurl);
myHttpWebRequest.Method = "POST";
myHttpWebRequest.Headers.Add("Authorization", auth);
myHttpWebRequest.ContentType = "application/json; charset=utf-8";
StreamWriter streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream(), System.Text.Encoding.UTF8);
streamWriter.Write(JSONRequest);
streamWriter.Flush();
streamWriter.Close();
// Get the response
HttpWebResponse httpResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Create a new read stream for the response body and read it
StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream());
SqlString result = streamReader.ReadToEnd();
return (result);
}
Needed to send User:Pass as network credentials instead of auth. and use 'application/json' as content type.
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static SqlString POST(String POSTurl, String auth,String user, String pass, String ContentType, SqlString JSONRequest)
{
SqlPipe pipe = SqlContext.Pipe;
//Create Request
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(POSTurl);
myHttpWebRequest.Method = "POST";
if (user != null) { myHttpWebRequest.Credentials = new NetworkCredential(user, pass); }
else if (auth!=null) { myHttpWebRequest.Headers.Add("Authorization", auth); }
myHttpWebRequest.ContentType = ContentType;
StreamWriter streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream());
streamWriter.Write(JSONRequest);
streamWriter.Flush();
streamWriter.Close();
// Get the response
HttpWebResponse httpResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Create a new read stream for the response body and read it
StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream(), System.Text.Encoding.UTF8);
SqlString result = streamReader.ReadToEnd();
return (result);
}

Getting content from httpwebresponse exception

My remote server is throwing a web exception as bad request. But I know there is more information included in the error than what I get. If I look at the details from the exception it does not list the actual content of the response. I can see the content-type, content-length and content-encoding only. If I run this same message through another library (such as restsharp) I will see detailed exception information from the remote server. How can I get more details from the response since I know the remote server is sending them?
static string getXMLString(string xmlContent, string url)
{
//string Url;
string sResult;
//Url = ConfigurationManager.AppSettings["UserURl"] + url;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/xml";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(xmlContent);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
sResult = result;
}
}
return sResult;
}
EDIT : Have you tried with a simple try-catch to see if you can get more details ?
try
{
var response = (HttpWebResponse)(request.GetResponse());
}
catch(Exception ex)
{
var response = (HttpWebResponse)ex.Response;
}
In my recherches in an answer for you, I noticed that in code there was something about encoding, that you didn't specified. Look here for exemple with such code.
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
}
Or here, in the doc, also.
// Creates an HttpWebRequest with the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for the response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Gets the stream associated with the response.
Stream receiveStream = myHttpWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r\nResponse stream received.");
Have you tried with such ?

C# WP8 async HttpWebRequest Post with xml request message

i've been reading here for quite a long time, but in this case i'm not getting any further.
I'm rather new to Windows Phone development and facing the following problem.
I'm calling a webservice were I have to post a xml request message. I've got the code working in regular c# (see code below)
private static string WebRequestPostData(string url, string postData)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
return sr.ReadToEnd().Trim();
}
}
}
But for Windows Phone (8) development it needs to be async. After searching the web, and trying the various samples given here I came to the following code:
private async void DoCallWS()
{
string url = "<my_url>";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/xml";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
string requestXml = "<my_request_xml>";
// convert request to byte array
byte[] requestAsBytes = Encoding.UTF8.GetBytes(requestXml);
// Write the bytes to the stream
await stream.WriteAsync(requestAsBytes , 0, requestAsBytes .Length);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
//return reader.ReadToEnd();
string result = reader.ReadToEnd();
}
}
}
The string result has the value of my request xml message i'm trying to sent....
I'm aware that async void methodes are not preferred but i will fix that later.
I've also tried to following the solution as described by Matthias Shapiro (http://matthiasshapiro.com/2012/12/10/window-8-win-phone-code-sharing-httpwebrequest-getresponseasync/) but that caused the code to crash
Please point me in the right direction :)
Thnx Frank
What you're doing is only writing to the request stream. You're missing the code which reads from the response.
The reason you're getting back your request xml is that you reset the request stream and read from that exact stream.
Your method should look as follows:
private async Task DoCallWSAsync()
{
string url = "<my_url>";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/xml";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
string requestXml = "<my_request_xml>";
// convert request to byte array
byte[] requestAsBytes = Encoding.UTF8.GetBytes(requestXml);
// Write the bytes to the stream
await stream.WriteAsync(requestAsBytes , 0, requestAsBytes .Length);
}
using (WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(httpWebRequest.BeginGetResponse, httpWebRequest.EndGetResponse, httpWebRequest))
{
var responseStream = responseObject.GetResponseStream();
var sr = new StreamReader(responseStream);
string received = await sr.ReadToEndAsync();
return received;
}
}

Creating CURL Request ASP.NET

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();

Categories