Issues with posting JSON - c#

So on my client (windows phone 8.1 app) I have posted a JSON just for testing, here is the code for this:
public async void SendJSON()
{
try
{
string url = "http://posttestserver.com/post.php?dir=karim";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
string json = "{ \"my\" : \"json\" }";
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
}
catch(Exception ex)
{
}
}
Now I'm trying to figure out, from the www.myurl.com how would I retrieve what has been posted from the mobile app using a Web Service?
UPDATE
When I debug these lines, it runs perfectly without breaking nor falling within the catch. However when looking at where it should post to (the results are here http://www.posttestserver.com/data/2015/12/14/karim/) it doesn't post anything.
Does anyone know what I'm doing wrong?
BTW: it already has results there because I have done this directly from my desktop.

Not sure what you are trying to do but if you want to inspect your http requests fiddler is a good choice. Since your are using windows phone apps you can configure the windows phone emulator to proxy through fiddler.
Here is a blog post how to set this up: http://blogs.msdn.com/b/wsdevsol/archive/2013/06/05/configure-the-windows-phone-8-emulator-to-work-with-fiddler.aspx - Configure the Windows Phone 8 Emulator to work with Fiddler
// Edit: Have you considered to use HttpClient
var httpClient = new HttpClient();
string resourceAddress = "http://posttestserver.com/post.php?dir=karim";
string postBody = "{ \"my\" : \"json\" }"
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await httpClient.PostAsync(resourceAddress, new StringContent(postBody, Encoding.UTF8, "application/json"));
Code is from the top of my head so you might have to tweak it... and of course you need to handle error cases and/or retry, etc
HTH

If you just want to see, what have you send, you can use this http://posttestserver.com
Otherwise there is not easy way how to force some endpoint to retrieve data. There must but set up server, which is allowing it, proccessing it, storing it etc.
If you POST anything to http://posttestserver.com/post.php it will return you this message
Successfully dumped 0 post variables. View it at
http://www.posttestserver.com/data/2015/12/15/00.19.29177030164 Post
body was 134 chars long.
So just print somewhere your response and you will get the exact url

You should use fiddler to see the outputted content:
http://www.telerik.com/fiddler
Windows Phone 8.1 Emulator not proxying through Fiddler

Related

How to specify message body in a WebClient?

In the console, I follow up a call the site I'm on is is making and I can see the address (some.site.com/gettoken), message header and something that FF calls Message Body. It's in the latter that I can see the credentials that I've entered on the site that are being sent.
So, I've got the URL and the message body. Then, I've tried to implement the behavior using C# for my Azure service layer like so.
String url = #"https://some.site.com/gettoken";
String credentials = "username=super&password=secret";
using (WebClient client = new WebClient())
{
String output = client.UploadString(url, credentials);
result = output;
}
However, I get error 400 - bad result. What did I miss?
I've googled for some stuff but the only remotely relevant hits are talking about the upload methods, which I've used. Am I barking up the wrong tree entirely or just missing something tiny? Some people seem to get it to work but they're not tokenizing around. And I'm not certain enough to determine whether it's of relevance or not.
So, as a summary of what has been discussed in the comments: you can use the more modern HttpClient instead.
Note that this is the System.Net.Http.HttpClient and not Windows.Web.Http.HttpClient.
An example implementation could look like this:
public async Task<string> SendCredentials()
{
string url = #"https://some.site.com/gettoken";
string credentials = "username=super&password=secret";
using(var client = new HttpClient())
{
var response = await client.PostAsync(url, new StringContent(credentials));
return await response.Content.ReadAsStringAsync();
}
}
You might also be interested in System.Net.Http.FormUrlEncodedContent which allows you to pass in the parameters and their values so you don't have to construct the credentials value yourself.
More information on async/await.

WebRequest.WebResponse unavailable in universal Windows 8.1/Windows Phone 8.1 C# app

I'm trying to do a very simple HTTP request on a URL in order to use the returned data. Everything I've done before and everything I'm reading on MSDN indicates that this should work:
string url = "http://www.abettergeek.com/misc/hovservice.php";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
However, GetResponse() apparently doesn't exist for HttpWebRequest, even though it seems like it should.
What am I doing wrong here?
Edit:
I figured out how to use HttpClient correctly. I was trying to assign the result of the HttpClient stream to a variable, which wasn't working the way I wanted it to.
I ended up using the following:
Uri north = new Uri("http://www.abettergeek.com/misc/hovservice.php");
HttpClient northc = new HttpClient();
string northr = await northc.GetStringAsync(north);

Some help posting to ASP.NET Web API with C#

I have been playing with ASP.NET Web API. I am looking to see can I post to a method I have built which simply returns back the object I have POSTED:
On The Accounts Controller:
// POST /api/accounts
public Account Post(Account account)
{
return account;
}
Code Used To Post:
public void PostAccount()
{
// http://local_ip/api/accounts
var uri = string.Format("{0}", webServiceRoot);
var acc = new Account();
acc.AccountID = "8";
acc.AccountName = "Mitchel Cars";
acc.AccountNumber = "600123801";
acc.SubscriptionKey = "2535-8254-8568-1192";
acc.ValidUntil = DateTime.Now;
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = 800;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Account));
xmlSerializer.Serialize(request.GetRequestStream(), acc);
var response = (HttpWebResponse)request.GetResponse();
XmlSerializer serializer = new XmlSerializer(typeof(Account));
var newAcc = (Account)serializer.Deserialize(response.GetResponseStream());
}
I have removed any error checking or any boiler plate code to make it easier to read. This is strictly a spike just to under stand to to actually POST. My understanding is that you should write to the GetRequestStream(). All the reading and such seems to work ok but I never here back from the request.GetResponse();
If I do a simple get it works fine. I did see you can use a class called HTTPClient for doing this stuff but I can't use it as I need to get this working for WinForms, Silverlight and Windows Phone all based on .Net 3.5
Any help pushing POCO's to the server would be a great help, cheers!
ADDITIONAL INFO:
Currently I get no error, the test app just hangs.
If I turn off the WebAPI project I get a server not found response.
I have not changed any routes or any of that.
Gets to the same controller work.
You will need to close the response stream. Most examples I see also show setting the content length. You may be better to serialize to a memory stream and then use the length of that stream as the Content-Length. Unfortunately in .net 3.5 there is no CopyStream so you may have to write that yourself.
If you want to use the HttpClient, you can install the download the REST starter Kit. and use the DLLs as external DLLs
http://forums.asp.net/t/1680252.aspx/1

RPC to java based Google App Engine from C# Client

I'm having a lot of problems calling a Java based Google App Engine server from a C# client
This is how my client code looks like:
// C# Client
static void Main(string[] args)
{
const string URL = "http://localhost:8888/googlewebapptest7/greet";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "text/x-gwt-rpc; charset=utf-8";
string content = "<?xml version='1.0'?><methodCall><methodName>greetServlet.GetName</methodName><params></params></methodCall>";
byte[] contentBytes = UTF8Encoding.UTF8.GetBytes(content);
request.ContentLength = contentBytes.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(contentBytes, 0, contentBytes.Length);
}
// get response
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
string res = new StreamReader(responseStream).ReadToEnd();
Console.WriteLine("response from server:");
Console.WriteLine(res);
Console.ReadKey();
}
The server is basically the Google default web project with an additional method:
public String GetName()
{
return "HI!";
}
added to GreetingServiceImpl.
Everytime I run my client, I get the following exception from the server:
An IncompatibleRemoteServiceException was thrown while processing this call.
com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException: This application is out of date, please click the refresh button on your browser. ( Malformed or old RPC message received - expecting version 5 )
I would like to keep it in plain HTTP requests.
Any idea what's going on?
As Nick pointed out you're trying to emulate GWT's RPC format. I tried that too :)
Then I took different approach. I used Google Protocol Buffers as encoder/decoder over HTTP(S).
One of my projects is desktop application written in C#. Server-side is also C#.Net. Naturally we use WCF as transport.
You can plug-in Protocol Buffers into WCF transport. You'll have same interface configuration both for C# client and Java server. It's very convenient.
I'll update this answer with code-samples when I'm less busy with work.
I never found a good way to use XML based RPC on the Google App Engine. Instead i found this excellent JSON library with tutorial:
http://werxltd.com/wp/portfolio/json-rpc/simple-java-json-rpc/
it works very well!

HTTP Post in C# console app doesn't return the same thing as a browser request

I have a C# console app (.NET 2.0 framework) that does an HTTP post using the following code:
StringBuilder postData = new StringBuilder(100);
postData.Append("post.php?");
postData.Append("Key1=");
postData.Append(val1);
postData.Append("&Key2=");
postData.Append(val2);
byte[] dataArray = Encoding.UTF8.GetBytes(postData.ToString());
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://example.com/");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = dataArray.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(dataArray, 0, dataArray.Length);
requestStream.Flush();
requestStream.Close();
HttpWebResponse webResponse = (HttpWebResponse)httpRequest.GetResponse();
if (httpRequest.HaveResponse == true) {
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseReader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
String responseString = responseReader.ReadToEnd();
}
The outputs from this are:
webResponse.ContentLength = -1
webResponse.ContentType = text/html
webResponse.ContentEncoding is blank
The responseString is HTML with a title and body.
However, if I post the same URL into a browser (http://example.com/post.php?Key1=some_value&Key2=some_other_value), I get a small XML snippet like:
<?xml version="1.0" ?>
<RESPONSE RESULT="SUCCESS"/>
with none of the same HTML as in the application. Why are the responses so different? I need to parse the returned result which I am not getting in the HTML. Do I have to change how I do the post in the application? I don't have control over the server side code that accepts the post.
If you are indeed supposed to use the POST HTTP method, you have a couple things wrong. First, this line:
postData.Append("post.php?");
is incorrect. You want to post to post.php, you don't want post the value "post.php?" to the page. Just remove this line entirely.
This piece:
... WebRequest.Create("http://example.com/");
needs post.php added to it, so...
... WebRequest.Create("http://example.com/post.php");
Again this is assuming you are actually supposed to be POSTing to the specified page instead of GETing. If you are supposed to be using GET, then the other answers already supplied apply.
You'll want to get an HTTP sniffer tool like Fiddler and compare the headers that are being sent from your app to the ones being sent by the browser. There will be something different that is causing the server to return a different response. When you tweak your app to send the same thing browser is sending you should get the same response. (It could be user-agent, cookies, anything, but something is surely different.)
I've seen this in the past.
When you run from a browser, the "User-Agent" in the header is "Mozilla ...".
When you run from a program, it's different and generally specific to the language used.
I think you need to use a GET request, instead of POST. If the url you're using has querystring values (like ?Key1=some_value&Key2=some_other_value) then it's expecting a GET. Instead of adding post values to your webrequest, just put this data in the querystring.
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://example.com/?val1=" + val1 + "&val2=" + val2);
httpRequest.Method = "GET";
httpRequest.ContentType = "application/x-www-form-urlencoded";
....
So, the result you're getting is different when you POST the data from your app because the server-side code has a different output when it can't read the data it's expecting in the querystring.
In your code you a specify the POST method which sends the data to the PHP file without putting the data in the web address. When you put the information in the address bar, that is not the POST method, that is the GET method. The name may be confusing, but GET just means that the data is being sent to the PHP file through the web address, instead of behind the scenes, not that it is supposed to get any information. When you put the address in the browser it is using a GET.
Create a simple html form and specify POST as the method and your url as the action. You will see that the information is sent without appearing in the address bar.
Then do the same thing but specify GET. You will see the information you sent in the address bar.
I believe the problem has something to do with the way your headers are set up for the WebRequest.
I have seen strange cases where attempting to simulate a browser by changing headers in the request makes a difference to the server.
The short answer is that your console application is not a web browser and the web server of example.com is expecting to interact with a browser.
You might also consider changing the ContentType to be "multipart/form-data".
What I find odd is that you are essentially posting nothing. The work is being done by the query string. Therefore, you probably should be using a GET instead of a POST.
Is the form expecting a cookie? That is another possible reason why it works in the browser and not from the console app.

Categories

Resources