I want to send a message to LinkedIn user from my connections. I try the following code:
string s = #"<?xml version='1.0' encoding='UTF-8'?>
<mailbox-item>
<recipients>
<recipient>
<person path='/people/1234567' />
</recipient>
</recipients>
<subject>Congratulations on Test.</subject>
<body>Test Here</body>
</mailbox-item>";
string url = "https://api.linkedin.com/v1/people/~/mailbox?oauth2_access_token=XXXXXXXXXXXX";
HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
webRequest.Timeout = 10000;
webRequest.ContentType = "text/xml";
webRequest.Method = "POST";
using (var writer = new StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(s);
}
WebResponse response = webRequest.GetResponse();
I get an exception "The remote server returned an error: (400) Bad Request." on the last string. What is incorrectly?
Related
I am getting an error on HttpWebRequest.GetRequest() when trying to send xml request on one web service for response. This same request working from Postman. Please guide in right direction to solve this. Below is a XML Body text and code.
string xmlMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<GetDetail xmlns=\"http://tempuri.org/\">"
"<strNo>22101</strNo> <baCode></baCode> <authkey>xxxx</authkey><source>xxxx</source>"
"</GetDetail>" "</soap:Body>" "</soap:Envelope>";
byte[] requestInFormOfBytes = System.Text.Encoding.ASCII.GetBytes(xmlMessage);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://xxxxxxx.xx/xxxx/GetDetail");
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.Headers.Add("SOAPAction", "http://tempuri.org/GetDetail");
webRequest.Headers.Add("Client-Id", "XXXXXXXXXXXXX");
webRequest.Headers.Add("Client-Secret", "XXXXXXXXXXXXXXXXX");
webRequest.Accept = "application/xml";
webRequest.ContentLength = requestInFormOfBytes.Length;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
Error give on this line.
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(requestInFormOfBytes, 0, requestInFormOfBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader respStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
string receivedResponse = respStream.ReadToEnd();
Console.WriteLine(receivedResponse);
respStream.Close();
response.Close();
Thanks for all to give right direction, its resolved by (1) Test with FrameWork 4.6
(2) Use SecurityProtocoltype.Tls12 (refer - https://stackoverflow.com/a/32789483/5694613).
I am using XDocument to manually build a SOAP request and send it using HTTPWebRequest. The final output of the XDocument object is valid and when I capture and send it to the end point using SOAPUI it works fine, however; I have been unable to get this to work using HTTPWebRequest. I receive internal server server errors, but nothing really specific that I can work from. I am excluding the XDocument object for brevity. Any guidance would be appreciated.
var _url = "http://xxx.xx.x.xx:9191/aa/bb/cc/dd";
var _action = "http://xxx.xx.x.xx:9191/aa/bb/cc/dd?op=submit";
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(_url);
webRequest.Headers.Add(#"SOAPAction", _action);
webRequest.Credentials = new NetworkCredential("xxxxx", "xxxxxx");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
using (Stream stream = webRequest.GetRequestStream())
{
xd.Save(stream);
}
// get the response from the completed web request.
string soapResult;
try
{
using (WebResponse webResponse = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Response.Write(soapResult);
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
Response.Write("Status Code : " + ((HttpWebResponse) ex.Response).StatusCode);
Response.Write("Status Description : " + ((HttpWebResponse) ex.Response).StatusDescription);
}
}
UPDATE (included small sample of SOAP):
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<enrollment xmlns="xxxxxxxxxxx">
<asOfDate xmlns="">2018-01-01</asOfDate>
<activate xmlns="">false</activate>
<subscription xmlns="">
<receiptDate>2018-06-01</receiptDate>
<accountMatchData>
<accountHccIdentifier>
<accountHccIdentificationNumber>xxxxxxxxxx</accountHccIdentificationNumber>
</accountHccIdentifier>
<asOfDate>2018-01-01</asOfDate>
</accountMatchData>
<informationSourceCode>
<codeEntry>3</codeEntry>
</informationSourceCode>
</subscription>
</enrollment>
</s:Body>
</s:Envelope>
UPDATE (Solved):
I cannot believe it was something as stupid as how it was sending the credentials. I used the below code to generate the credentials and add them to the HTTPWebRequest and it worked.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("xxxx" + ":" + "xxxxxxx"));
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(_url);
webRequest.Headers[HttpRequestHeader.Authorization] = string.Format(
"Basic {0}", credentials);
I have done a request SOAP with SOAPUI and all works fine. The request is equal to the xmlString with Basic Authentication type.
I need to do this request into a c# solution but my code doesn't work:
string xmlString = #"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:soap=""http://soap.service.tracking.sda.it/"">
<soapenv:Header/>
<soapenv:Body>
<soap:doIt>
<arg0>
<!--Optional:-->
<codCliente>00000000001</codCliente>
<!--1 to 10 repetitions:-->
<datiSpedizione>
<!--You may enter the following 3 items in any order-->
<!--Optional:-->
<idLdv>000001</idLdv>
<!--Optional:-->
<ultimoStato>N</ultimoStato>
</datiSpedizione>
<descrizioneStatus>E</descrizioneStatus>
<!--Optional:-->
<postazione>00001</postazione>
<tipologiaCliente>SDA</tipologiaCliente>
</arg0>
</soap:doIt>
</soapenv:Body>
</soapenv:Envelope>";
HttpWebRequest request = CreateWebRequest("https://ws.sda.it/TRACKING","user","pass");
request.PreAuthenticate = true;
request.ReadWriteTimeout = 32000;
request.Timeout = 32000;
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(xmlString);
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
}
}
And this is the createWebRequestMethod:
public static HttpWebRequest CreateWebRequest(string url, string user, string pass)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Credentials = new NetworkCredential(user, pass);
webRequest.Headers.Add(#"SOAPAction", "TRACKING");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
When i try to use this code i go into an exception of "Null reference" in the request.GetResponse()
I've a code block like this:
const string webServiceUrl = "https://test.xyxyx.com/App/Services/wService.svc?wsdl";
var postString = string.Format("Parameter1={0}&Parameter2={1}&Parameter3={2}&Parameter4={3}&Parameter5={4}&Parameter6={5}&Parameter7={6}&Parameter8={7}", "AA", "AB", "AC", "BA", "BB", BC, 5, 7);
const string contentType = "text/xml; charset=utf-8";
HttpWebRequest webRequest = WebRequest.Create(webServiceUrl) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = contentType;
webRequest.Accept = "text/xml";
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();
responseReader.Close();
webRequest.GetResponse().Close();
I get the error on this line:
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
The remote server returned an error: (400) Bad Request
Why I get this? I tried some different methods, but result is the same. What can I do?
I think the problem is that you're posting to ?wsdl url.
Also, your content is not xml.
Generally, you can examine the content of the returned page, it may have some more details.
Finally check out .NET: Simplest way to send POST with data and read response .
I'm trying to make a SOAP request in C#. Using SoapUI, I have successfully made the required request, so I basically copied the request string into the LoadXml of the following C# code:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(#"https://w8cert.iconnectdata.com:443/FleetCreditWS/services/FleetCreditWS0200");
webRequest.Headers.Add(#"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(#"<?xml version=""1.0"" encoding=""utf-8"" ?><soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:main=""http://fleetCredit02.comdata.com/maintenance/"" xmlns:wsse=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"">
<soapenv:Header>
<wsse:Security>
<wsse:UsernameToken>
<wsse:Username>{MyUserName}</wsse:Username>
<wsse:Password>{MyPassword}</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<main:ProprietaryIntradayRequest>
<startDate>2018-02-06</startDate>
<maskCardFlag>false</maskCardFlag>
</main:ProprietaryIntradayRequest>
</soapenv:Body>
</soapenv:Envelope>");
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
WebResponse response;
try
{
using (response = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
}
}
}
catch (WebException e)
{
StreamReader str = new StreamReader(e.Response.GetResponseStream());
System.Diagnostics.Debugger.Break();
}
This code throws the ever-fun (500) Internal Server Error on the "using (response = webRequest.GetResponse())" line. I even tried to capture the web exception response, but get the same 500 error.
Can anyone see something I'm missing that would cause the same request to work in SoapUI, but fail in C#?