Console application, first webrequest doesn't get response, later does, why? - c#

I am developing console application for API integration. This follow fetching token in first request and then getting report in second request after passing token.
string token = GetToken(app_id); // API call, which is working fine and getting token
string reportquerystring = "path?token=" + token;
WebRequest req = WebRequest.Create(#reportquerystring);
req.Method = "GET";
req.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
var resp = req.GetResponse() as HttpWebResponse;
using (Stream downloadstream = resp.GetResponseStream())
{
XmlDocument reportxml = new XmlDocument();
string filename = "location\\";
string reportxmlString = (new StreamReader(downloadstream)).ReadToEnd();
reportxml.LoadXml(reportxmlString);
string json = JsonConvert.SerializeXmlNode(reportxml);
System.IO.File.WriteAllText(filename + "data_" + app_id + ".txt", json);
}
Here when I run this code while debugging, on the first call of download report, response xml is empty, when I drag debugger again before call, in the same run, then it gets response properly. But until and unless I figure out the reason why first call to download report API is not working or how I can make it work, I can not proceed.
Any suggestions ?

Related

JIRA web request causes issues

I am trying to to extract data from Jira via JIRA REST API from a c# application. to do so I execute this method :
public string RunQuery(JiraRessource resource, string project_id, int startAt, int maxResults, string method = "GET")
{
string url = string.Format(m_BaseUrl);
if (project_id != null)
{
string jql = "search?jql=project=" + project_id;
url = string.Format("{0}{1}", url, jql);
}
string jqr = "&startAt=" + startAt + "&maxResults=" + maxResults;
url = string.Format("{0}{1}", url, jqr);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
string base64Credentials = GetEncodedCredentials();
request.Headers.Add("Authorization", "Basic " + base64Credentials);
string result = string.Empty;
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
return result;
}
}
}
I execute this method in a loop in order to be able to get all issues after I read that the REST API only gives 50 issues each time. I get errors such as "connection timed out" or "unable to read data from the transport connection". I searched online and all i found is that the connection to the server is lost but I do not know how to solve this.
If anyone knows anything about the reason why I'm getting this error or how to solve it, I will be very thankful.
A few things to try below. If any of these work, it will help you get to the source of the problem.
Try with a request for a small amount of data:
string url = "<your base url>/search?jql=startAt=1&maxResults=1&fields=created";
Try that same url in a web browser (log in to Jira first with the same creds you are using in your C# code)
Try with this code before the call:
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{
return true;
};
Check the permissions in Jira for the user id you are using for the api call.

C# HTTP request 401 and 500 error

I've been working on the Walmart API but I keep getting either the 401 error or the 500 error when I run the code
public void post()
{
byte[] data = Encoding.ASCII.GetBytes(
$"username={user}&password={password}");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://marketplace.walmartapis.com/v2/feeds?feedType=item");
request.Method = "POST";
request.Accept = "application/xml;";
request.ContentLength = data.Length;
request.Headers.Add("WM_SVC.NAME", "Walmart Marketplace");
request.Headers.Add(authId);
request.Headers.Add("WM_CONSUMER.ID", user);
request.Headers.Add( time);
request.Headers.Add(CorId);
using (Stream stream = request.GetRequestStream ())
{
stream.Write(data , 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
MessageBox.Show(responseContent);
}
where authID is a signature generated from a jar file provided by walmart
time is also generated from the jar file
CorID is a randomly generated number
and user is the user id.
here is the link that describes the header parameters. Did I miss something in my header?
https://developer.walmartapis.com/#getting-started
There are multiple problems with your request. First, you are submitting a feed, but sending it as an application/xml when it should be a multipart/form-data request. Beyond this, your headers aren't set up properly and there is currently a major problem with submitting multipart/form-data requests to Walmart using C#. I have not seen a post from anyone successfully sending a feed to Walmart via C#. I am currently using C# to execute a batch file that then fires a modified version of the Walmart Java SDK which is capable of sending the multipart/form-data requests.
The reponse below is for any request other than feeds. I would start with the example listed below to get familiar with how you need to set your headers up. This is going to work for the majority of Walmart interfacing, but if the request is a feed style request, you will either need to come up with a better solution to the multipart/form-data issue, use the Java SDK, or wait for the C# SDK. If someone reads this and has a better answer as to how to submit feeds via C# exclusively I would love to hear about it!
Here is an example of an application/xml request that works.
string timestamp = CurrentTimeMillis().ToString().Trim();
string query = #"orders/"+poID+"/acknowledge";
string request = v3BaseUrl + query; //Constructed URI
string stringToSign = consumerId + "\n" +
request.Trim() + "\n" +
"POST" + "\n" +
timestamp + "\n";
string signedString = signData(stringToSign); //Your signed string
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);
webRequest.Accept = "application/xml";
webRequest.ContentType = "application/xml";
webRequest.Method = "POST";
webRequest.Headers.Add("WM_SVC.NAME", "Walmart Marketplace");
webRequest.Headers.Add("WM_SEC.AUTH_SIGNATURE", signedString);
webRequest.Headers.Add("WM_CONSUMER.ID", consumerId);
webRequest.Headers.Add("WM_SEC.TIMESTAMP", timestamp.ToString().Trim());
webRequest.Headers.Add("WM_QOS.CORRELATION_ID", Guid.NewGuid().ToString());
webRequest.Headers.Add("WM_CONSUMER.CHANNEL.TYPE", channelType);
webRequest.ContentLength = 0;
webRequest.Timeout = Timeout.Infinite;
webRequest.KeepAlive = true;
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
success = true;
}
}

JSON post from c# fails with 500 error

I have a c# winforms app in which I'm trying to call into a web service for which I control the code (on both ends). I know the web service is fine because I can call it from jquery with no problems and valid json is returned. But when I call it from c#, I get this error: "The remote server returned an error: (500) Internal Server Error." In the debugger I cannot glean any more details than that.
Here is my c# caller code:
private string GetMemberCheckInData() {
string response = string.Empty;
string fullURL = RootServiceURL + "MemberCheckIn";
var httpWebRequest = (HttpWebRequest) WebRequest.Create(fullURL);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
string json = "{\"scanCode\":\"" + APIKey + "\"," +
"\"siteID\":\"2\"," +
"\"revenueGroupID\":\"0\"," +
"\"employeeID\":\"12345\"}";;
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
response = streamReader.ReadToEnd();
}
}
return response;
}
Here is the literal JSON that is being sent:
{"scanCode":"***8G9V3MA39H0N****","siteID":"2","revenueGroupID":"0","employeeID":"12345"}
Here is the c# web service code (works fine when called from jquery):
[WebMethod]
public void MemberCheckIn(string scanCode, int siteID, int revenueGroupID, int employeeID)
{
...code is never reached...
}
The web service function is never actually entered; I confirmed this with the debugger. When I call it from jquery, I can debug right into it. So it seems the request is being rejected by the .net runtime or IIS or something.
Any ideas what I am doing wrong?
Your webmethod is expecting you to pass parameters in to it.
string fullURL = RootServiceUrl + "MemberCheckIn?scanCode=X&siteID=1...etc.

How to make a POST to Eloqua by rest api?

I am working with eloqua 10.
I need to create Email in eloqua by using their rest api from an aspx web page.But am get 404 Bad Request.
Given below is the code sample for the POST request that I tried.
string authenticateStr = eloquainstance + #"\" + username + ':' + password;
byte[] bytesToEncode = Encoding.UTF8.GetBytes(authenticateStr);
string encodedText = Convert.ToBase64String(bytesToEncode);
string requrl = "/assets/email";
string requestBody = "<subject>Test subject</subject>" +
"<senderName>Ajai Test</senderName>" +
"<senderEmail>amani#suyati.com</senderEmail>" +
"<emailGroupId>9</emailGroupId>" +
"<htmlContent>This is a test email templete created trough rest api.This is for testing purpose only</htmlContent>"+
"<type>Email</type>" +
"<name>Email By api</name>";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl + requrl);
request.Headers.Add("Authorization", "Basic " + encodedText);
request.Accept = "application/xml";//"application/x-www-form-urlencoded";
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = requestBody.Length;
//write body to text
byte[] body = System.Text.Encoding.UTF8.GetBytes(requestBody);
Stream dataStream = request.GetRequestStream();
dataStream.Write(body, 0, requestBody.Length);
dataStream.Close();
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Please correct me if anything wrong in my code.
Can anybody tried a post using eloqua rest api, if so can you share a sample code to make a POST request to eloqua from c#.Any help be appreciable.
Not sure whether you've got this working yet as some time has passed since you asked this, but you can find a whole set of samples for using eloqua's topliners site:
http://topliners.eloqua.com/community/code_it/blog/2012/10/08/eloqua-rest-api--open-source-c-samples
Looking at your code I think you may need to escape the html body
I would also consider writing a class to represent the email object and then use restsharp to simplify the process of serialising the request and handling the response.
Also experiment with test requests using fiddler.

C# - HttpWebResponse redirect checker

I'm trying to code a redirect checker, the solution I have was just banged together this morning so it's not the most efficient but it does everything I need it to do apart from one thing:
It only ever checks two sites before stopping, no errors occur, it just stops on the "request.GetResponse() as HttpWebResponse;" line for the third page.
I've tried using different sites and changing the combination of pages to check but it only ever checks two.
Any ideas?
string URLs = "/htmldom/default.asp/htmldom/dom_intro.asp/htmldom/dom_examples2.asp/xpath/default.asp";
string sURL = "http://www.w3schools.com/";
string[] u = Regex.Split(URLs, ".asp");
foreach (String site in u)
{
String superURL = sURL + site + ".asp";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(superURL);
request.Method = "HEAD";
request.AllowAutoRedirect = false;
var response = request.GetResponse() as HttpWebResponse;
String a = response.GetResponseHeader("Location");
Console.WriteLine("Site: " + site + "\nResponse Type: " + response.StatusCode + "\nRedirect page" + a + "\n\n");
}
Aside from the fact that it will break if a WebException is ever thrown, I believe the reason it's just stopping is that you never dispose of your response. If you have multiple URLs served actually by the same site, they'll use a connection pool - and by not disposing of the response, you're not releasing the connection. You should use:
using (var response = request.GetResponse())
{
var httpResponse = (HttpWebResponse) response;
// Use httpResponse here
}
Note that I'm casting here instead of using as - if the response isn't an HttpWebResponse, an InvalidCastException on that line is more informative than a NullReferenceException on the next line...

Categories