Not able to receive json from Android app developed using C# - c#

This is the code which I have written on the app side, which is being developed using Xamarin
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(ApiUrl);
objRequest.Method = "POST";
objRequest.ContentType = "application/x-www-form-urlencoded";//"application/json;charset=utf-8";
objRequest.Headers.Add("Authentication", "web60134");
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] arrRequest;
arrRequest = utf8Encoding.GetBytes(JsonReq);
objRequest.ContentLength = arrRequest.Length;
Stream requestStream = objRequest.GetRequestStream();
requestStream.Write(arrRequest, 0, arrRequest.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)objRequest.GetResponse();
StreamReader streamReader = new StreamReader(res.GetResponseStream());
string result = streamReader.ReadToEnd();
This is the code written on the server side which is PHP
$recvd = $_POST['TH_ET_LoginProcess'];
$recvdArr = json_decode($recvd);
I tried using file_get_contents("php://input") but both the methods are returning null or nothing.
What is the best way to read JSON at web server using PHP in such scenario?

Best is a quite subjective term.
However what I am successfully using RestSharp in an Xamarin Android solution.
I also highly recommend PostMan and Fiddler for troubleshooting your service.
Regarding your code:
You should be disposing those objects that are disposable, preferable with the 'using' statement. This includes HttpWebResponse object is as well as the Stream ones.

Related

Connectiong to API with C# NetworkingClient

Can someone help me with following API connection with C#. Never done any API connections before so i am a little unsure how it work. This is for a universal windows application so it will be using c# and XMAL.
Is it possible to do the following PHP API call below using C#:
<?php
$uri = 'http://api.football-data.org/v1/soccerseasons/354/fixtures/?matchday=22';
$reqPrefs['http']['method'] = 'GET';
$reqPrefs['http']['header'] = 'X-Auth-Token: YOUR_TOKEN';
$stream_context = stream_context_create($reqPrefs);
$response = file_get_contents($uri, false, $stream_context);
$fixtures = json_decode($response);
?>
Basically all i need to know is if it is even possible.
Thanks in advance.
It can be something like this (result is as text but you can json too):
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://api.football-data.org/v1/soccerseasons/354/fixtures/?matchday=22");
request.Headers.Add("AUTHORIZATION", "Basic YTph");
request.ContentType = "text/html";
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string ResultAsText = stream.ReadToEnd().ToString();
Here is my favorite example of calling a WEB API: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
It shows how to use HttpClient, uses async / await and introduces Formatters.

Translating COM objects (or possibly XMLHTTP) in Coldfusion to C#

I've been converting a bunch of files from Coldfusion to C#, and all has been going swimmingly until now. I'm pretty much learning ColdFusion as I go, and I barely ever write in C# so I'm stuck here. Can anybody help explain how I would go about translating this chunk of code into C#?
<cfobject type="COM" action="Create" name="objServerXMLHttp" class="msxml2.ServerXMLHTTP.3.0">
<cfset objServerXMLHttp.open("POST", "http://URL", True , "Me.User", "Me.Password")>
<cfset objServerXMLHttp.setRequestHeader("Content-Type", "text/xml")>
<cfset objServerXMLHttp.setRequestHeader("charset", "utf-8")>
<cfset objServerXMLHttp.send("#XMLRequest#")>
<cfset thread = CreateObject("java", "java.lang.Thread")>
For some background, I'm basically just taking info from a database, surrounding it with XML tags in a string, creating an XML file out of the string, and now here I am.
The direct translation is easy in C# 4.0 (VS2010) with the dynamic keyword:
dynamic objServerXMLHttp = Activator.CreateInstance(Type.GetTypeFromProgID("msxml2.ServerXMLHTTP.3.0"));
objServerXMLHttp.open("POST", "http://chrdevweb:8080/mellibase/webservice/rest", true, "Me.User", "Me.Password");
objServerXMLHttp.setRequestHeader("Content-Type", "text/xml");
objServerXMLHttp.setRequestHeader("charset", "utf-8");
objServerXMLHttp.send("#XMLRequest#");
So just to break it down as to what this coldfusion code is doing (which you probably know anyway):
It is instantiating an object type msxml2.ServerXMLHTTP in memory.
It is then using that object to construct an XML document.
It is then sending that (via HTTP POST) to the URL: http://chrdevweb:8080/mellibase/webservice/rest
And lastly, it seems to instantiate a java object (not sure its related).
So in asp.net using c#, the post code would like so:
HttpWebRequest request=null;
Uri uri = new Uri(url);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using(Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
string result=string.Empty;
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader (responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
The result variable in the end would hold your response. The 'url' is the url you are posting to, and 'postData' is your xml string.
To construct the XML doc, you can use XMLdocument in c#, or you can just put a string together.
PS: this is untested, so there may be a syntax error somewhere :)

C# HttpWebRequest with XML Structured Data

I'm developing the client-side of a third party webservice. The purpose is that I send xml-file to the server.
How should I attach the xml-file to the httpwebrequest? What contentType is needed? More suggestions?
I cannot use mtom or dime.ie because I am using httpwebrequest. I am unable to use WCF either.
Here is a very basic method of sending XML structured data using HttpWebRequest (by the way you need to use request.ContentType = "application/xml";) :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(myUrl));
request.Method = "POST";
request.ContentType = "application/xml";
request.Accept = "application/xml";
XElement redmineRequestXML =
new XElement("issue",
new XElement("project_id", 17)
);
byte[] bytes = Encoding.UTF8.GetBytes(redmineRequestXML.ToString());
request.ContentLength = bytes.Length;
using (Stream putStream = request.GetRequestStream())
{
putStream.Write(bytes, 0, bytes.Length);
}
// Log the response from Redmine RESTful service
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Logger.Info("Response from Redmine Issue Tracker: " + reader.ReadToEnd());
}
I use this at one of my projects (NBug) to submit an issue report to my Redmine issue tracker which accepts XML structured data over web requests (via POST). If you need further examples, you can get a couple of fully featured examples here: http://nbug.codeplex.com/SourceControl/list/changesets (click 'Browse' under 'Latest Verion' label on the right then navigate to "NBug\Submit\Tracker\Redmine.cs")

Programmatically call webmethods in C#

I'm trying to write a function that can call a webmethod from a webserive given the method's name and URL of the webservice. I've found some code on a blog that does this just fine except for one detail. It requires that the request XML be provided as well. The goal here is to get the request XML template from the webservice itself. I'm sure this is possible somehow because I can see both the request and response XML templates if I access a webservice's URL in my browser.
This is the code which calls the webmethod programmatically:
XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
Stream stm = req.GetRequestStream();
doc.Save(stm);
stm.Close();
WebResponse resp = req.GetResponse();
stm = resp.GetResponseStream();
StreamReader r = new StreamReader(stm);
Console.WriteLine(r.ReadToEnd());
Following on from the comments above. If you have a WSDL file that describes your service you use this as the information required to communicate with your web service.
Using a proxy class to communicate with your service proxy is an easy way to abstract yourself from the underlying plumbing of HTTP and XML.
There are ways of doing this at run-time - essentially generating the code that Visual Studio generates when you add a web service reference to your project.
I've used a solution that was based on: this newsgroup question, but there are also other examples out there.
FYI, your code is missing using blocks. It should be more like this:
XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
using (Stream reqstm = req.GetRequestStream())
{
doc.Save(reqstm);
}
using (WebResponse resp = req.GetResponse())
{
using (Stream respstm = resp.GetResponseStream())
{
using (StreamReader r = new StreamReader(respstm))
{
Console.WriteLine(r.ReadToEnd());
}
}
}

Anyone have sample code for doing a "chunked" HTTP streaming download of one web directly to a upload to a separate web server?

Background - I'm trying to stream an existing webpage to a separate web application, using HttpWebRequest/HttpWebResponse in C#. One issue I'm striking is that I'm trying to set the file upload request content-length using the file download's content-length, HOWEVER the issue seems to be when the source webpage is on a webserver for which the HttpWebResponse doesn't provide a content length.
HttpWebRequest downloadRequest = WebRequest.Create(new Uri("downloaduri")) as HttpWebRequest;
using (HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse)
{
var uploadRequest = (HttpWebRequest) WebRequest.Create(new Uri("uripath"));
uploadRequest.Method = "POST";
uploadRequest.ContentLength = downloadResponse.ContentLength; // ####
QUESTION : How could I update this approach to cater for this case (when the download response doesn't have a content-length set). Would it be to somehow use a MemoryStream perhaps? Any sample code would be appreciated. In particular is there a code sample someone would have that shows how to do a "chunked" HTTP download & upload to avoid any issues of the source web server not providing content-length?
Thanks
As I already applied in the Microsoft Forums, there are a couple of options that you have.
However, this is how I would do it with a MemoryStream:
HttpWebRequest downloadRequest = WebRequest.Create(new Uri("downloaduri")) as HttpWebRequest;
byte [] buffer = new byte[4096];
using (MemoryStream ms = new MemoryStream())
using (HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse)
{
Stream respStream = downloadResponse.GetResponseStream();
int read = respStream.Read(buffer, 0, buffer.Length);
while(read > 0)
{
ms.Write(buffer, 0, read);
read = respStream.Read(buffer, 0, buffer.Length);
}
// get the data of the stream
byte [] uploadData = ms.ToArray();
var uploadRequest = (HttpWebRequest) WebRequest.Create(new Uri("uripath"));
uploadRequest.Method = "POST";
uploadRequest.ContentLength = uploadData.Length;
// you know what to do after this....
}
Also, note that you really don't need to worry about knowing the value for ContentLength a priori. As you have guessed, you could have set SendChunked to true on uploadRequest, and then just copied from the download stream into the upload stream. Or, you can just do the copy without setting chunked, and HttpWebRequest (as far as I know) will buffer the data internally (make sure AllowWriteStreamBuffering is set to true on uploadrequest) and figure out the content length and send the request.

Categories