Unable to make http call from c# DLL - c#

I have created a c# library in Visual Studio 2019 on my mac. I am trying to expose a method in my dll which should have the capacity to make an http call and return the response.
But I am getting the error Cannot send a content-body with this verb-type.
I am very new to c#, so I just copy-pasted code from online. Please show me what wrong I am doing.
My Library,
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace ImageTrainer
{
public class Trainer
{
public static void TrainImage()
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create("https://www.abcd.com/rest/city/search/Bang");
request.Method = "GET";
request.ContentType = "application/json";
// // request.ContentLength = DATA.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
// // requestWriter.Write(DATA);
requestWriter.Close();
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Console.WriteLine(response);
// responseReader.Close();
// Console.WriteLine(response);
}
}
}
and I am using the library in another console application.
using System;
using ImageTrainer;
namespace ImageTrainerTest
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Trainer.TrainImage();
}
}
}
What mistake am I making?

Remove these 2 lines:
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Close();
As you are making GET request, you should not have any body, otherwise you should use POST verb.

Related

Send XML document over soap

Following is my code:
Method(SendXmlDocument) will take in as parameter an XML document, URL, and the SOAP action and make a request to a web service. I have to use HttpClient class to make the request to the web service.
using System;
using System.Net;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
namespace HttpClientStatus
{
class WebServiceClient
{
public void SendXmlDocument(XmlDocument fi , string URL , string action)
{
XmlDocument soapEnvelopeXml = fi;
HttpWebRequest webRequest = CreateWebRequest(URL, action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
}
class Program
{
static void Main(string[] args)
{
var _u = "http://xxxxxxxxx/Service1.asmx";
var _a = "http://xxxxxxxxx/Service1.asmx/action";
XmlDocument d = new XmlDocument();
d.Load("C://Users//gmzmdz//Desktop//course.xml");
WebServiceClient ob = new WebServiceClient();
ob.SendXmlDocument(d, _u, _a);
}
}
}
My Question is that following pure xml document will be sent or not. That this method make a request to web service or not. How do I will know about it that request has been made successful? Then, I have to print the response on the console that comes back from the web service.

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!

403 Forbidden error REST Call

I am building a REST Client in C#. I am getting forbidden 403 error. Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using restservice.webref;
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace restservice
{
class getUUID
{
private const string URL = "http://XXX.XXXX.com/ws410/XXXXX/XX/XX";
public void getProductID()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.Credentials = new NetworkCredential("XXXX", "XX");
request.Accept = #"text/html, application/xhtml+xml, */*";
request.Referer = #"http://www.somesite.com/";
request.Headers.Add("Accept-Language", "en-GB");
request.UserAgent = #"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
request.Host = #"www.my.XXX.com";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.ContentType = "application/json";
/*StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(false);
requestWriter.Close();*/
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
String htmlString = reader.ReadToEnd();
}
/*
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
responseReader.Close();*/
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
}
}
}
}
I have also given the credentials as well as enabled the default credentials. Still I get the 403 error.
Please can you help?
This might be related to Env. security profile . For example i had the same issue . Added below in spring security yml file securityCollections: - name: "Security" patterns: - "/rootpath/*"
Http Forbidden error usually occurs when you are trying to call the server and server is not allowing the request.
The API that you are calling should whitelist your application IP.
Check if there is any http header restrictions on the API that you are calling.
For Infra related changes you can check this: link

Calling Soap web service over HTTP giving exception "Connection close"

I am calling third party Web service over HTTP but it is failing to connect in WPF application/Console Application. Exception is connection close. Wondering why it is closed though same SOAP message works in SOAP UI. Can I give Action with URN as I copyed from SOAP UI. Please suggest what is wrong. Since it is not using browser so cros domain problem should not be.
My C# code is as follows.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
namespace CTWpfApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
CallWebService();
}
public static void CallWebService()
{
var _url = "https://myService.com/webservices/ct/services/4.1";
var _action = "urn:provider/interface/ctservices/getCPNInstances";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// Start the asynchronous operation to get the response
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation /* I'm getting the exception Connection Close."*/
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.KeepAlive = false;
webRequest.Timeout = 300000;
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:ns1=""urn:dictionary:com.ct.webservices""><SOAP-ENV:Header xmlns:wsse=""http://docs.myses.org/wss/2004/01/200401-wss-wssecurity-secext-1.0.xsd""><wsse:Security SOAP-ENV:mustUnderstand=""1""><wsse:UsernameToken><wsse:Username>fiwjiueji</wsse:Username><wsse:Password Type=""http://docs.myses.org/wss/2004/01/200401-wss-username-token-profile-1.0#PasswordText"">tjrrfrsi</wsse:Password></wsse:UsernameToken></wsse:Security></SOAP-ENV:Header><SOAP-ENV:Body><ns1:getCPNInstances></ns1:getCPNInstances></SOAP-ENV:Body></SOAP-ENV:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
}
}
Take out the webRequest.KeepAlive = false in the CreateWebRequest method.
When using HTTP/1.1, Keep-Alive is on by default. Setting KeepAlive to false may result in sending a Connection: Close header to the server. -From http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.keepalive.aspx

Cannot set CookieContainer due to the state of the HttpWebRequest object error?

I am currently trying to login and get cookies to a remote server using windows phone 7 silverlight in visual studio. I managed to login and get a successful result for login, but when I try to put in the codes to get cookies, it just failed.
It produced error "Cannot set CookieContainer due to the state of the HttpWebRequest object." on my code "request.CookieContainer = new CookieContainer();"
Can anyone helps me? I can't seem to find the error and I try to look at the documentation and examples but with no luck. Below is my full codes on windows phone 7.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;
namespace Testing_Login_
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, RoutedEventArgs e)
{
//HttpWebRequest req = WebRequest.Create();
string POST_ADDRESS = "http://mywebsite.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(POST_ADDRESS, UriKind.Absolute));
request.Method = "POST";
// don't miss out this
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
}
// Sumbit the Post Data
void RequestReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
Stream stream = request.EndGetRequestStream(asyncResult);
// Hack for solving multi-threading problem
// I think this is a bug
this.Dispatcher.BeginInvoke(delegate()
{
// Send the post variables
StreamWriter writer = new StreamWriter(stream);
writer.Write("username=" + textBoxUsername.Text + "&password=" + passwordBoxSTAMP.Password);
writer.Flush();
writer.Close();
request.CookieContainer = new CookieContainer();
request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
});
}
// Get the Result
void ResponseReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
this.Dispatcher.BeginInvoke(delegate()
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
// get the result text
string result = reader.ReadToEnd();
if (result == "TRUE")
{
MessageBox.Show("Login Successful!");
//CookieCollection cookieValue = response.Cookies;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies", FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(isfs))
{
foreach (Cookie cookieValue in response.Cookies)
{
sw.WriteLine("Cookie: " + cookieValue.ToString());
}
sw.Close();
}
}
}
//MessageBox.Show(cookieValue.ToString());
}
else if (result == "ICRED")
{
MessageBox.Show("Username or Password incorrect!");
}
else
{
MessageBox.Show("Unknown Error!"+result);
}
});
}
private void ReadFromIsolatedStorage()
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs =
isf.OpenFile("CookieExCookies", FileMode.Open))
{
using (StreamReader sr = new StreamReader(isfs))
{
textBoxCookies.Text = sr.ReadToEnd();
sr.Close();
}
}
}
}
}
}
Move the line:-
request.CookieContainer = new CookieContainer();
out of RequestReady and put it in buttonLogin_Click just after you have constructed it.
OR since you aren't re-using it anywhere ditch line altogether.
OR if in fact for things to really work you need to re-use it then construct and hold it somewhere else (such as a field in the class) and assign it to each Request object created before you invoke any BeginGetRequestStream or BeginGetResponse.

Categories