Sorry for virtually begging for help here but I've been tasked to work on the above and cannot find any adequate resources to help me. Here's the details:
The company has Identity management software which provides an SPML (SOAP) 'feed' of changes to user entitities
(If I've got this right) the SPML driver makes a POST request to a URL on my server which sends those changes
Whatever sits under that URL has to then process the posted information (XML)
Point 3 is my bit. I have no idea what to write. Asmx? Aspx? Ashx? Commodore 64 cassette tape? Apparently the SPML driver needs a 200 response - it will get that anyway when the processing has taking place no? Is there anything more to it that I'm not getting?
Any help, pointers, guidance or advising me to give up and get a new hobby, would be much appreciated.
Thanks.
EDIT..............
Have got a simple soap driver going (for the purposes of testing) which posts xml to an aspx page which then, in turn, consumes the POST and saves the xml. Thanks to J Benjamin (below) and http://www.eggheadcafe.com/articles/20011103.asp for the kick-start.
SOAP DRIVER (works on page load)
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(MySite.FileRoot + "testing\\testxml.xml");
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create("http://localhost/mysite/testing/reader.aspx");
req.ContentType = "text/xml; charset=\"utf-8\"";
req.Method = "POST";
req.Headers.Add("SOAPAction", "\"\"");
Stream stm = req.GetRequestStream();
doc.Save(stm);
stm.Close();
WebResponse resp = req.GetResponse();
stm = resp.GetResponseStream();
StreamReader r = new StreamReader(stm);
Response.Write(r.ReadToEnd());
}
SOAP READER (reads xml posted when called)
protected void Page_Load(object sender, EventArgs e)
{
String Folderpath = "c:\\TestSOAP\\";
if (!Directory.Exists(Folderpath))
{
Directory.CreateDirectory(Folderpath);
}
Response.ContentType = "text/xml";
StreamReader reader = new StreamReader(Request.InputStream);
String xmlData = reader.ReadToEnd();
String FilePath = Folderpath + DateTime.Now.ToFileTimeUtc() + ".xml";
File.WriteAllText(FilePath, xmlData);
}
The next step is to try consume the SPML service (which is a Java-driven Novell type thing) - if I have any problems, I will post back here!!
Thanks all.. :)
Maybe I'm misunderstanding, but this sounds similar to how I'm handling URLs in my web service. We're handling logic based on URLs, do the logic, wrap it up in XML and respond with the XML object. Here's a simple example (by simple, I mean one of the few that doesn't require authentication)
The code below simply returns an XML object containing an AppSetting. The XML response is below as well (with some identifying values removed).
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "External/Application/{ApplicationGUID}/APIHost/")]
public Response GetAPIHostName(Request request, string ApplicationGUID)
{
Response response = new Response();
try
{
APIHost apiHost = new APIHost
{
APIHostname = System.Configuration.ConfigurationManager.AppSettings["PlayerAPIHostname"]
};
response.ResponseBody.APIHost = apiHost;
response.ResponseHeader.UMResponseCode = (int) UMResponseCodes.OK;
}
catch (GUIDNotFoundException guidEx)
{
response.ResponseHeader.UMResponseCode = (int)UMResponseCodes.NotFound;
response.ResponseHeader.UMResponseCodeDetail = guidEx.Message;
}
catch (Exception ex)
{
UMMessageManager.SetExceptionDetails(request, response, ex);
if (request != null)
Logger.Log(HttpContext.Current, request.ToString(), ex);
else
Logger.Log(HttpContext.Current, "No Request!", ex);
}
response.ResponseHeader.HTTPResponseCode = HttpContext.Current.Response.StatusCode;
return response;
}
/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
200
200
localhost
Related
I'm trying to download REST API response content as (original format) excel (.xlsx)
My request url is :- https://www.connect2nse.com/extranet-api/member/file/download/1.0?segment=CM&folderPath=/Reports&filename=07141_AR1_Dec22.xlsx
And I'm downloading the 07141_AR1_Dec22.xlsx file.
So, I have used this method to return the response content
public static string DownloadFileName()
{
try
{
var client = new RestClient("https://www.connect2nse.com/extranet-api/member/file/download/1.0?segment=CM&folderPath=/Reports&filename=07141_AR1_Dec22.xlsx");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer eyJhbGciOweSUzI1NiJ9.eyJtZW1iZXJDZCI6IjA3MTQxIiwic3ViIjoiMDcxNDEiLCJsb2dpbklkIjoiYm5yaG8xIiwiaXNzIjoiYm5yaG8xIiwiZXhwIjoxNjc0ODA0NDE0LCJpYXQiOjE2NzQ4MDA4MTQsImp0aSI6ImEwY2U3NjNkLWY1OWUtNDY2Yy1hMmMwLTUwNGQwZDgzOTQwYiJ9.UCnkkvTTi9fZjWWak5deXgxPEqMG16FQP4Cy_u1cR0hQb-xQ4LAhbfpMtFz1WXQ4fz7ZmRhkR1i9JXY4w32lzQ");
request.AddHeader("Cookie", "HttpOnly");
var body = #"";
request.AddParameter("text/plain", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
//Console.WriteLine(response.Content);
return response.Content;
}
catch (Exception)
{
throw;
}
}
And I'm calling this method in btnDownload_Click event in windows forms application
private void btnDownload_Click(object sender, EventArgs e)
{
string downloadfile = DownloadFileName();
string _tradelogfile = Application.StartupPath + "\\07141_AR1_Dec22.xlsx";
using (System.IO.StreamWriter file = new System.IO.StreamWriter(_tradelogfile, true))
{
file.WriteLine(downloadfile);
}
}
The DownloadFileName method is returning the output like below image
So if I keep execute the program the file is downloading at specified location
Like below example
While I'm opening the file it is throwing warning errors and file is not opening like below
In the postman response also I'm getting the response like below image
And I have read this article for better understanding but it not helped to me.
Please suggest me where I did the mistake and how to save(download) this REST API response content as excel format(.xlsx).
Should I use any dll or is my code issue ?
Please suggest.
I am working on a c# console application where I am making a Http Post request to a web api by using xml file and I'm kind of new to XML and web services but I figured out the following code for the request but failed to pass xml data to the method
static void Main(string[] args)
{
string desturl=#"https://xyz.abcgroup.com/abcapi/";
Program p = new Program();
System.Console.WriteLine(p.WebRequestPostData(desturl, #"C:\Applications\TestService\FixmlSub.xml"));
}
public string WebRequestPostData(string url, string postData)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
return sr.ReadToEnd().Trim();
}
}
}
For obvious reasons the above code throws 404 error as I think I am not passing the xml data properly
May I know how I can fix this?
You're not posting xml, your posting the string C:\Applications\TestService\FixmlSub.xml
Change your method call from:
System.Console.WriteLine(p.WebRequestPostData(desturl, #"C:\Applications\TestService\FixmlSub.xml"));
to
var xml = XElement.Load(#"C:\Applications\TestService\FixmlSub.xml");
System.Console.WriteLine(p.WebRequestPostData(desturl, xml.ToString(SaveOptions.DisableFormatting));
If you are trying to learn post / receive, go for it. But there are open source libraries that are already well tested to use if you want to use them.
The non-free version of Servicestack.
And their older free-version. I think the older free version is great. I've never tried the newer one. You deal with objects, like say an Employee and pass that to the library and it does the translation to xml or whatever the web-service wants.
You can post whole strings if you want. They have great extension methods to help you with that too.
I want to get the http request header and also the post data from a given URL.... how to do that?.... I have to display http request header, http response header, content of a given url and post data...
Below is my code for that....
private void button1_Click(object sender, EventArgs e)
{
try
{
string url = txtUrl.Text;
HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse Response = (HttpWebResponse)WebRequestObject.GetResponse();
HttpStatusCode code = Response.StatusCode;
txtStatus.Text = code.ToString();
txtResponse.Text = Response.Headers.ToString();
// Open data stream:
Stream WebStream = Response.GetResponseStream();
// Create reader object:
StreamReader Reader = new StreamReader(WebStream);
// Read the entire stream content:
string PageContent = Reader.ReadToEnd();
// Cleanup
Reader.Close();
WebStream.Close();
Response.Close();
txtContent.Text = PageContent;
// var request = WebRequest.Create("http://www.livescore.com ");
//var response = request.GetResponse();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
But how to get post data and http request header that i dont know...pls help
It's not very clear what you are trying to accomplish with mixed references to GET, POST, and request and response headers.
If you can make the request you want in a browser and use Fiddler to intercept it, you can use the Fiddler add-on Request-To-Code to generate C# code that will perform the request. The generated code would probably be a good place for you to start - from something that works and with which you can further tinker.
Fiddler is a great way to learn more about HTTP.
I have a web client I'm creating in Silverlight. I am trying to get it to communicate it with my web services on my server through GET and POST requests and JSON. The GET requests work fine and I'm able to parse the JSON on the Silverlight end. The POST requests however dont seem to work. The server reads that there is a POST request, but the POST array is empty.
Ive tried two pieces of code to send the POST requests, but both are resulting in the same response - an empty array.
The first Silverlight code I tried was:
public MainPage()
{
InitializeComponent();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://www.dipzo.com/game/services.php"));
request.Method = "POST";
request.ContentType = "application/json";
request.BeginGetRequestStream(new AsyncCallback(OnGetRequestStreamCompleted), request);
}
private void OnGetRequestStreamCompleted(IAsyncResult ar)
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
using (StreamWriter writer = new StreamWriter(request.EndGetRequestStream(ar)))
{
writer.Write("name=david");
}
request.BeginGetResponse(new AsyncCallback(OnGetResponseCompleted), request);
}
private void OnGetResponseCompleted(IAsyncResult ar)
{
//this.GetResponseCoimpleted.Visibility = Visibility.Visible;
// Complete the Flickr request and marshal to the UI thread
using (HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)ar.AsyncState).EndGetResponse(ar))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string results = reader.ReadToEnd();
}
}
}
The second piece I tried was:
private void WebClient_Click(object sender, RoutedEventArgs e)
{
Test t1 = new Test() { Name = "Civics", Marks = 100 };
DataContractJsonSerializer jsondata = new DataContractJsonSerializer(typeof(Test));
MemoryStream mem = new MemoryStream();
jsondata.WriteObject(mem, t1);
string josnserdata = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient cnt = new WebClient();
cnt.UploadStringCompleted += new UploadStringCompletedEventHandler(cnt_UploadStringCompleted);
cnt.Headers["Content-type"] = "application/json";
cnt.Encoding = Encoding.UTF8;
cnt.UploadStringAsync(new Uri("http://www.dipzo.com/game/services.php"), "POST", josnserdata);
}
void cnt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var x = e;
}
The code on the server to consume the service is in PHP and is essentially:
var_dump($_POST)
This should output whatever is coming into the post array. I've tested it with a simple PHP client and it works. Just can't get it to work in silverlight. In silverlight I just keep getting an empty array.
You should change the Content-type to application/x-www-form-urlencoded and not application/json which is not a known type yet.
Not that I think anyone is still paying attention tot his old question, but I'm betting that the problem was that it actually WAS getting to the server, but that the server routed the result back to the SL application. This is the behavior I'm seeing with a similar situation from SL5 usingWebClient.UploadStringAsync.
I'm about to implement/test a technique I ran across yesterday which uses a dynamically built, "real" page post from SL; I'll report my findings shortly.
UPDATE -- THIS SOLUTION WORKS:
http://www.codeproject.com/Tips/392435/Using-HTTP-Form-POST-method-to-pass-parameters-fro
I've just tested it in my application (SL5 inside MVC) and it works just fine. Make sure you check the HttpContext.Request.Form["fieldname"] to get the value(s) that you want. I used this technique to submit JSON and was able to return a generated Word document for the user.
Once I implemented this I was able to get rid of the unnecessary WebClient that I was attempting to use before.
I am trying to send an HTTPWebRequest POST XML data to my WCF service.
However when setting a breakpoint in my service, it is hit, but my widgetStream is empty when I try to read it. Even if I read it from a StreamReader.
Does anyone know what I am doing wrong?
My WCF service looks like this:
[WebInvoke(UriTemplate = "widgets", Method = "POST"]
public void CreateWidget(Stream widgetStream)
{
try
{
XElement e = XElement.Load(widgeStream);
//...
}
catch (Exception ex)
throw;
}
}
My client is trying to connect and post an XML resource to an HTTP URL like so:
public static void CreateWidget(Widget myWidget)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:29858/myservice/widgets");
request.Method = "POST";
request.ContentType = "text/xml";
string xml = myWidget.ToXML().ToString();
request.ContentLength = xml.Length;
Stream s = request.GetRequestStream();
StreamWriter sr = new StreamWriter(s);
sr.Write(xml);
sr.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
If anyone could please help that would be appreciated!
[WebInvoke(UriTemplate = "widgets", Method = "POST", RequestFormat=WebMessageFormat.Xml, BodyStyle=WebMessageBodyStyle.Bare]
[XmlSerializerFormat]
public void CreateWidget(XElement widget){...}
Try this on your service. I just ran into a similar issue this week. I haven't tried using the HTTPWebRequest object but I can post raw XML to the service using Fiddler.
You might need to change Content-Type on the client to "application/xml" rather than "text/xml".