How to Call a WebService without using WebReference? - c#

I want to know if there is someone who had use a Class to Call a WebService, this WS receives an integer after the organizational references and responds into a json file,
Actually my issue is to call the webservice without using a webreference, and read the json file and parse it into a dictionary ,
I appreciate your help
Best Regards, i let you my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using Dimex.ChangeSAP.Core.Utilities;
namespace Dimex.ChangeSAP.Core.Utilities
{
class ConsumirWebService
{
public void ConsumirWS()
{
Dimex.ChangeSAP.Core.Entities.Seguridad.Usuario users = new Dimex.ChangeSAP.Core.Entities.Seguridad.Usuario();
int idUsuaro = users.IdUsuario;
try
{
System.Net.WebRequest req = System.Net.WebRequest.Create("http://192.168.8.97/PassportPruebas/api/partners?enterprise_system_id=1&organizational_reference=" + idUsuaro);
//req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending.
//Post'ed Faked Forms should be name=value&
string postData = "OPERATION_NAME=ADD_REQUEST&TECHNICIAN_KEY=90BA&INPUT_DATA=" + sendXML;
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
System.Net.WebResponse resp = req.GetResponse();
if (resp == null)
{
return null;
}
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
string respuesta = sr.ReadToEnd().Trim();
return respuesta;
}
catch (Exception ex)
{
return "";
//throw or return an appropriate response/exception
}
}
}
}

Well Actually here is my code for anyone with this kind of issue too,
public static string LlamarWebService(string url)
{
try
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "application/json";
req.Method = "GET";
System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
string respuesta = sr.ReadToEnd().Trim();
return respuesta;
}
catch (Exception ex)
{
throw ex;
// return "";
//throw or return an appropriate response/exception
}
}

you can create a proxy class using wsdl utility or svcutil in visualstudiocommand prompt enter command wsdl.exe /out:[path and name of the file] /language:CS

Related

Need a simple Google Speech API example for .NET

I need a simple Google Speech API example for .NET in which I upload a voice file and receive the text.
Thanks.
Just worked for me, you can create a class as follow:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
namespace GoogleAPI{
public class GoogleSpeech
{
public string URL { get; set; }
public void GetSpeechTranscript(string filePath)
{
try
{
FileStream fileStream = File.OpenRead(filePath);
MemoryStream memoryStream = new MemoryStream();
memoryStream.SetLength(fileStream.Length);
fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
byte[] resBytes = memoryStream.GetBuffer();
HttpWebRequest request = null;
request = (HttpWebRequest)HttpWebRequest.Create(this.URL + "&key=YOUR_API_KEY");
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "POST";
request.ContentType = "audio/x-flac; rate=44100";
request.ContentLength = resBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(resBytes, 0, resBytes.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StreamReader reqStream = new StreamReader(response.GetResponseStream());
var result = reqStream.ReadToEnd();
Console.WriteLine(result);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
Hope this help!

C# Httpwebrequest Log In System

The following code should log user in, but it does not work. The code uses 9gag as an example, but the general idea should work elsewhere too. The user does not get access his/hers profile.
What is wrong with the code?
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace ttp_B
{
internal class Program
{
private static void Main(string[] args)
{
bool flag = false;
//string word_to_stop = "profile";
string urltosite = "https://9gag.com/login"; // site that i'm trying to log in
string emailaddress = "";
string password = "";
var coo = new System.Net.CookieContainer();
try
{
var request = System.Net.WebRequest.Create(urltosite) as System.Net.HttpWebRequest;
request.CookieContainer = coo;
request.Method = "POST";
request.Proxy = new WebProxy("127.0.0.1", 8888); // fiddler
//some extra headers
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0";
using (var stream = request.GetRequestStream())
{
byte[] buffer =
Encoding.UTF8.GetBytes(
string.Format(
"csrftoken=&next=http%3A%2F%2F9gag.com%2F&location=1&username={0}&password={1}", emailaddress, password));
//this text of request is correct I guess. Got it from fiddler btw.
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}
using (var response = request.GetResponse() as HttpWebResponse)
{
coo.Add(response.Cookies); // adding cookies, just to make this working properly
using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
{
string http_code = sr.ReadToEnd(); // gettin' that new html document
//flag = (http_code.Contains(word_to_stop)); // looking for word that I'm sure exist after succesfull loggin' in
//if(flag == true)
//{
// console.writeline("Works");
//}
}
}
}
catch (WebException e)
{
Console.Write(e.ToString());
}
}
}
}
As far as I can see, the request stream isn't closed before you go for the response.
simplified it should look like this:
var stream = request.GetRequestStream();
tStream(buffer, 0, buffer.Length);
//close the stream
tStream.Close();
//go for the response
request.GetResponse();

How to capture a response token sent by a REST API after a request?

I am working on consuming a REST API and I am using basic authentication where password is encoded to Base64 as follows
private XmlDocument sendXMLRequest(string requestXml)
{
string destinationUrl = "https://serviceapi.testgroup.com/testtp/query";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("API_TEST_NR:Testnol1$"));
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.Method = "POST";
request.ContentLength = bytes.Length;
//request.Connection = "keep-alive";
request.ContentType = "text/xml";
request.KeepAlive = true;
request.Timeout = 2000;
request.MediaType = "text/xml";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
Stream responseStream;
using (response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
responseStream = response.GetResponseStream();
XmlReader reader = new XmlTextReader(responseStream);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
try { reader.Close(); }
catch { }
try { responseStream.Close(); }
catch { }
try { response.Close(); }
catch { }
return xmlDoc;
}
}
try { response.Close(); }
catch { }
return null;
}
I'm kind of new to working on Web Api's and I know that the API responds with an access x-token after successful authorization based on the API documentaion and I am not sure how to access or capture it from the HTTP headers.
May I know a good way I can achieve this?
This is easier than I thought just capturing with its name.
string xtoken= response.Headers["custom-header"];
Console.WriteLine(xtoken);
Try this as below, represents, Request Data Using the WebRequest Class.In most cases, the WebRequest class is sufficient to receive data. However, if you need to set protocol-specific properties, you must cast the WebRequest to the protocol-specific type. For example, to access the HTTP-specific properties of HttpWebRequest, cast the WebRequest to an HttpWebRequest reference.
private XmlDocument GetRootLevelServiceDocument(
string serviceEndPoint, string oAuthToken)
{
XmlDocument xmlDoc = new XmlDocument();
HttpWebRequest request = CreateHttpRequest(serviceEndPoint,
oAuthToken);
using (HttpWebResponse response =
(HttpWebResponse)request.GetResponse())
{
using (XmlReader reader =
XmlReader.Create(response.GetResponseStream(),
new XmlReaderSettings() { CloseInput = true }))
{
xmlDoc.Load(reader);
string data = ReadResponse(response);
if (response.StatusCode != HttpStatusCode.OK)
{
LogMsg(string.Format("Error: {0}", data));
LogMsg(string.Format(
"Unexpected status code returned: {0}",
response.StatusCode));
}
}
}
return xmlDoc;
}

WCF to send request and receive response

Am learning WCF, i have been using webservices (.asmx) to send requests and receive responses to other webservices. On the webservices, i was able to invoke my webmethods and test them.
public string PrnNumber(string prnNumber)
{
bool flag = false;
try
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""><SOAP-ENV:Body><HelloWorld xmlns=""http://tempuri.org/"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><int1 xsi:type=""xsd:integer"">12</int1><int2 xsi:type=""xsd:integer"">32</int2></HelloWorld></SOAP-ENV:Body></SOAP-ENV:Envelope>");
flag = SendSOAP(soapEnvelop);
}
catch (Exception ex)
{
Util.LogMessage(ex.Message + ex.StackTrace, "Error", "err");
}
return "Success";
}
public bool SendSOAP(soapEnvelop)
{
bool flag = false;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http:***url");
req.Headers.Add("Accept-Encoding", "gzip,deflate");
req.Headers.Add("SOAPAction", "urn:lookupPRN");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
req.Proxy = null;
try
{
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(xml);
}
}
WebResponse response = req.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string responseString = reader.ReadToEnd();
Util.LogMessage(responseString, "Response", "res");
}
catch (Exception ex)
{
flag = false;
Util.LogMessage(ex.Message + ex.StackTrace, "Error", "err");
}
return flag;
}
finally
{
}
}
So i initially did this in .asmx and i would log both the requests and responses, How can i achive this using WCF? exactly the same logic, constructing the SOAP XML as plain XML in my code and invoke the partners's url for the response.
Suggest you spend some time reviewing a few WCF "Getting Started" articles.
The following provide a good, basic overview:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/getting-started-tutorial
http://www.codeproject.com/Articles/33995/Getting-Started-with-WCF
http://www.codeproject.com/Articles/42643/Creating-and-Consuming-Your-First-WCF-Service

How to use google speech recognition api in c#?

I want to get the audio file from c# and send to google speech recognition API for get the "speech to text" answer.
My code is like this:
try
{
byte[] BA_AudioFile = GetFile(filename);
HttpWebRequest _HWR_SpeechToText = null;
_HWR_SpeechToText =
(HttpWebRequest)HttpWebRequest.Create(
"https://www.google.com/speech-api/v2/recognize?output=json&lang=" + DEFAULT_LANGUAGE + "&key=" + key);
_HWR_SpeechToText.Credentials = CredentialCache.DefaultCredentials;
_HWR_SpeechToText.Method = "POST";
_HWR_SpeechToText.ContentType = "audio/x-flac; rate=44100";
_HWR_SpeechToText.ContentLength = BA_AudioFile.Length;
Stream stream = _HWR_SpeechToText.GetRequestStream();
stream.Write(BA_AudioFile, 0, BA_AudioFile.Length);
stream.Close();
HttpWebResponse HWR_Response = (HttpWebResponse)_HWR_SpeechToText.GetResponse();
if (HWR_Response.StatusCode == HttpStatusCode.OK)
{
StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
Console.WriteLine(SR_Response.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
This part is for upload the file.wav and get the response for the google API, which I find from Internet.
But my code always catches the exceptions:
you must write content length bytes to the request stream before calling at _HWR_SpeechToText.GetResponse(); But I already wroteh the ContextLength.
So my question is why my program failed? It's because the google link or the HTTPWebRequest I used inappropriately?
Is this the right place I got the API key?
Just tested this myself, below is a working solution if you have a valid API key.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace GoogleRequest
{
class Program
{
static void Main(string[] args)
{
try
{
FileStream fileStream = File.OpenRead("good-morning-google.flac");
MemoryStream memoryStream = new MemoryStream();
memoryStream.SetLength(fileStream.Length);
fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
byte[] BA_AudioFile = memoryStream.GetBuffer();
HttpWebRequest _HWR_SpeechToText = null;
_HWR_SpeechToText =
(HttpWebRequest)HttpWebRequest.Create(
"https://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key=YOUR_API_KEY_HERE");
_HWR_SpeechToText.Credentials = CredentialCache.DefaultCredentials;
_HWR_SpeechToText.Method = "POST";
_HWR_SpeechToText.ContentType = "audio/x-flac; rate=44100";
_HWR_SpeechToText.ContentLength = BA_AudioFile.Length;
Stream stream = _HWR_SpeechToText.GetRequestStream();
stream.Write(BA_AudioFile, 0, BA_AudioFile.Length);
stream.Close();
HttpWebResponse HWR_Response = (HttpWebResponse)_HWR_SpeechToText.GetResponse();
if (HWR_Response.StatusCode == HttpStatusCode.OK)
{
StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
Console.WriteLine(SR_Response.ReadToEnd());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}

Categories