HttpWebRequest 500 internal error but SOAPUI Works - soap

I got an error "The remote server returned an error: (500) Internal Server Error." with status code "ProtocolError"
HttpWebRequest webRequest = null;
XmlDocument soapEnvelopeXml = new XmlDocument();
string requestEnvelopeString = SerializerHelper.ToRequestEnvelopeString(request);
soapEnvelopeXml.LoadXml(requestEnvelopeString);
webRequest = (HttpWebRequest)WebRequest.Create(<<endpointUrl>>);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.KeepAlive = true;
webRequest.ProtocolVersion = HttpVersion.Version11;
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
try
{
using (WebResponse webResponse = webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string responseEnvelopeString = reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
string exMessage = ex.Message;
}
When I send the requestEnvelopeString directly through SOAPUI, it works, could anyone suggest how to troubleshoot this?

Found out that the problem is SOAP-ACTION header missing, SOAPUI will auto add to the request.
Thanks
mintssoul

Related

Server returned HTTP response code: 401 for URL: https://accounts.google.com/o/oauth2/token during generating access token

I am using the admin sdk API to retrieve all G Suite users. We require an access token for this. AWS is used to host our website. I've tried a few different codes to generate access token, but they always return error
"Server returned HTTP response code: 401 for URL: https://accounts.google.com/o/oauth2/token."
I have no idea why this error is occurring. My code is running smoothly, generating access token and retrieving every user domain wise in a local environment. Any help in why actually I am getting this error. have i missed something? any help in it.
This is my code.
private String getAccessToken()
{
String accessToken="";
try
{
Map<String,Object> params = new LinkedHashMap<>();
params.put("grant_type","refresh_token");
params.put("client_id",client_id);
params.put("client_secret",client_secret);
params.put("refresh_token",refresh_token);
StringBuilder postData = new StringBuilder();
for(Map.Entry<String,Object> param : params.entrySet())
{
if(postData.length() != 0)
{
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(),"UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()),"UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
URL url = new URL("https://accounts.google.com/o/oauth2/token");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.getOutputStream().write(postDataBytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
accessToken = json.getString("access_token");
return accessToken;
}
catch (Exception ex)
{
ex.printStackTrace();
}
return accessToken;
}

Http Post Flutter to SAP

Im trying to use http post to transfer data from flutter to SAP. I can get data without any problem, but post attempt is failing with code 403 (x-csrf-token invalid)
I had the same problem while working in C# but that was resolved using event handler, that triggers just before save (please see below extract of C# code) but i'm unable to find option in flutter. Please guide..
zZSSALE1SRVEntity.SendingRequest2 += new EventHandler<SendingRequest2EventArgs>(_container_SendingRequest_Enhance);
zZSSALE1SRVEntity.SaveChanges();
private void _container_SendingRequest_Enhance(object sender, SendingRequest2EventArgs e)
{
HttpWebResponse response;
string empty = string.Empty;
string str = string.Empty;
CookieContainer cookieContainer = new CookieContainer();
OdataSsaleDEV.ZZSSALE1_SRV_Entities zZSSALE1SRVEntity = new OdataSsaleDEV.ZZSSALE1_SRV_Entities(app_uri)
{
Credentials = credentials
};
string str1 ;
if (empty == string.Empty)
{
HttpWebRequest credentials = (HttpWebRequest)WebRequest.Create(zZSSALE1SRVEntity.BaseUri);
credentials.Method = "GET";
credentials.Headers.Add("X-CSRF-Token", "Fetch");
credentials.Credentials = zZSSALE1SRVEntity.Credentials;
cookieContainer = new CookieContainer();
credentials.CookieContainer = cookieContainer;
try
{
response = (HttpWebResponse)credentials.GetResponse();
}
catch (WebException webException)
{
MessageBox.Show(webException.Message);
return;
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
return;
}
empty = response.Headers.Get("X-CSRF-Token");
str = response.Headers.Get("Set-Cookie");
credentials.Abort();
}
if (empty != string.Empty)
{
e.RequestMessage.SetHeader("x-csrf-token", empty);
foreach (Cookie cooky in cookieContainer.GetCookies(zZSSALE1SRVEntity.BaseUri))
{
str1 = string.Concat(str1, ";", cooky.ToString());
}
e.RequestMessage.SetHeader("Cookie", str1.Substring(1));
}
Issue resolved.
Actually server requires session cookies (MYSAPSSO and SAP_SESSIONID) along with x-csrf-token.

How to add new account in Quickbooks

Below is the code I am using to try to add a new account to QuickBooks online. I am getting a (400) Bad Request. Can anyone help me with this.
HttpWebRequest httpWebRequest =
WebRequest.Create("https://sandbox-quickbooks.api.intuit.com/v3/company/xxxxxxxxxxx/account")
as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(httpWebRequest, ConsumerKeyQb, ConsumerSecQb, AccessKey, AccessSec));
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/xml";
string json = "{\"AccountType\":\"Accounts Receivable\",\"Name\":\"MySampleAccount\"}";
byte[] bytes = Encoding.UTF8.GetBytes(json);
httpWebRequest.ContentLength = bytes.Length;
using (Stream putStream = httpWebRequest.GetRequestStream())
{
putStream.Write(bytes, 0, bytes.Length);
}
HttpWebResponse httpWebResponse = null;
try
{
httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
}
catch (Exception e)
{
//return null;
var x = "Stop";
}
Thanks
400 response suggests that your API request payload is not correct.
You can try this call using IPP provided .net devkit.
https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits/0150_ipp_.net_devkit_3.0/0002_synchronous_calls/0001_data_service_apis
Using Dev-defined lib( sample call ) -
https://gist.github.com/IntuitDeveloperRelations/0913b4c224de758fde0a
Thanks

IPN Listner not working MVC3

My IPN listner is not working.when i tried with IPN listner Error is showing as follows "We're sorry, we could not send an IPN."
But i can access the IPN Handler url from browser.
here is my IPN handler Code.
public ActionResult IPN()
{
LogMessage ("entering ipn action ");
var formVals = new Dictionary<string, string>();
formVals.Add("cmd", "_notify-validate");
string response = GetPayPalResponse(formVals, true);
LogMessage ("IPN Response received: " + response + " <-- That was response. . . ");
if (response == "VALID")
{
LogMessage("Response Was Verified");
}
else
{
LogMessage("RESPONSE WAS NOT VERIFIED");
}
return Json("Sucess",JsonRequestBehavior.AllowGet);
}
string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
{
string paypalUrl = useSandbox
? "https://www.sandbox.paypal.com/cgi-bin/webscr"
: "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
StringBuilder sb = new StringBuilder();
sb.Append(strRequest);
foreach (string key in formVals.Keys)
{
sb.AppendFormat("&{0}={1}", key, formVals[key]);
}
strRequest += sb.ToString();
req.ContentLength = strRequest.Length;
string response = "";
using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(strRequest);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}
return response;
}
We had faced same issue before I feel it may be because your MVC Application may be published in shared hosting environment Then you have to follow some step to to make MVC RC application works
Here is the blog which help me to solve the issue.Please check this
http://helpnshareidea.blogspot.in/2013/11/mvc3-applications-in-windows-shared.html

Using .NET to get results from an API

I wanted to use the Rapidshare API in my .NET app, but I am confused on how you send the request and bring back the result. Do you use Winsock or another method?
URLs are like this:
http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=checkfiles_v1&files=288725357&filenames=my_upload.txt
Thanks.
Check out the System.Net namespace, specifically System.Net.WebClient.
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx
Use the WebClient Class.
http://msdn.microsoft.com/en-us/library/system.net.webclient%28VS.80%29.aspx
You can use this class to programatically interact with webpage. Here's some example code to log into a website. You can adapt this to interact with their web API:
HttpWebRequest request;
HttpWebResponse response;
CookieContainer cookies;
string url = "http://www.jaxtr.com/user/login.jsp";
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = true;
request.CookieContainer = new CookieContainer();
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StringBuilder sb = new StringBuilder();
StreamReader reader = new StreamReader(response.GetResponseStream());
while (!reader.EndOfStream)
{
sb.AppendLine(reader.ReadLine());
}
//Get the hidden value out of the form.
String fp = Regex.Match(sb.ToString(), "\"__fp\"\\svalue=\"(([A-Za-z0-9+/=]){4}){1,19}\"", RegexOptions.None).Value;
fp = fp.Substring(14);
fp = fp.Replace("\"", String.Empty);
cookies = request.CookieContainer;
//response.Close();
String requestString = "http://www.jaxtr.com/user/Login.action?tzOffset=6&navigateURL=&refPage=&jaxtrId=" + HttpUtility.UrlEncode(credentials.Username) + "&password=" + HttpUtility.UrlEncode(credentials.Password) + "&Login=Login&_sourcePage=%2Flogin.jsp&__fp="+HttpUtility.UrlEncode(fp);
request = (HttpWebRequest)WebRequest.Create(requestString);
request.CookieContainer = cookies; //added by myself
response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Response from login:" + response.StatusCode);
String messageText = (message.TruncateMessage && message.MessageText.Length > JaxtrSmsMessage.MAX_MESSAGE_LENGTH ? message.MessageText.Substring(JaxtrSmsMessage.MAX_MESSAGE_LENGTH) : message.MessageText);
String messageURL = "http://www.jaxtr.com/user/sendsms?CountryName=" + HttpUtility.UrlEncode(message.CountryName) + "&phone=" + HttpUtility.UrlEncode(message.DestinationPhoneNumber) + "&message=" + HttpUtility.UrlEncode(messageText) + "&bySMS=" + HttpUtility.UrlEncode(message.BySMS.ToString().ToLower());
request = (HttpWebRequest)WebRequest.Create(messageURL);
request.CookieContainer = cookies;
response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Response from send SMS command=" + response.StatusCode);
StringBuilder output = new StringBuilder();
using (Stream s = response.GetResponseStream())
{
StreamReader sr = new StreamReader(s);
while (!sr.EndOfStream)
{
output.AppendLine(sr.ReadLine());
}
}
response.Close();
}
else
{
Console.WriteLine("Client was unable to connect!");
}
}
catch (System.Exception e)
{
throw new SMSDeliveryException("Unable to deliver SMS message because "+e.Message, e);
}
This particular code logs into Jaxtr, a SMS messaging service, and sends an SMS message.