How do I Convert this Ajax Post request to C# - c#

I'm making a project in c# to get a facebook ID from any facebook URL. I an API that can helps but the code is using this Ajax POST code:
// get facebook id
$('#get-facebook-id').submit(function(event) {
$('#answer').html("<b>Working for you...</b>");
$.ajax({
type: 'POST',
url: 'https://codeofaninja.com/tools/get-facebook-id-answer.php',
data: $(this).serialize()
})
.done(function(data){
$('#answer').html(data);
$('#page_url_tb').val('')
})
.fail(function() {
alert( "Posting failed. Please try again." );
});
return false;
});
I'm trying to make my own code but is giving me an error. My code and my error down bellow.
private string getFbAccountID(string facebookurl)
{
var request = (HttpWebRequest)WebRequest.Create("https://codeofaninja.com/tools/get-facebook-id-answer.php");
var postData = "page_url="+facebookurl;
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
Error:
<br />
<b>Notice</b>: Undefined index: page_url in <b>/home/100661.cloudwaysapps.com/rpxdhcedbx/public_html/tools/get-facebook-id-answer.php</b> on line <b>3</b><br />
<br />
<b>Notice</b>: Undefined offset: 1 in <b>/home/100661.cloudwaysapps.com/rpxdhcedbx/public_html/tools/get-facebook-id-answer.php</b> on line <b>19</b><br />
<p>There was an error. Please try a different input.</p>
This is always giving me this error. I hope someone can helps me

I take it you're working on this exercise. :)
But to answer your question, you're not URL encoding facebookurl.
If you use one of the example Facebook URLs on their page, and watch the network traffic using the developer tools in the browser (F12), you will see this as the form data being sent: page_url=https%3A%2F%2Fwww.facebook.com%2Fpages%2FAndrew-Garfield%2F166865773328160
jQuery's serialize() function does that for you.
In C#, you can use WebUtility.UrlEncode:
var postData = "page_url=" + WebUtility.UrlEncode(facebookurl);

Here you have an alternative using System.Net.WebClient, it will make your code leaner:
private string getFbAccountID(string facebookurl)
{
using (var webClient = new System.Net.WebClient())
{
var formValues = new System.Collections.Specialized.NameValueCollection
{
{ "page_url", facebookurl }
};
var responseBytes = webClient.UploadValues(
"https://codeofaninja.com/tools/get-facebook-id-answer.php",
formValues
);
return System.Text.Encoding.UTF8.GetString(responseBytes);
}
}

Related

Calling PayU rest api (create order) returns html instead of json response

I'm trying to post an order to PayU payment gateway, using Rest Client tools like post man also I got the same issue.
I'm trying to post using C#, the order created successfully but the response is not as expected, it should be a json object contains the inserted order id and the redirect url , but the current is html response!
C# Code response :
My C# Code using restsharp library :
public IRestResponse<CreateOrderResponseDTO> CreateOrder(CreateOrderDTO orderToCreate)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var actionUrl = "/api/v2_1/orders/";
var client = new RestClient(_baseUrl);
var request = new RestRequest(actionUrl, Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddJsonBody(orderToCreate);
request.AddHeader("authorization", $"Bearer {_accessToken}");
request.AddHeader("Content-Type", "application/json");
var response = client.Execute<CreateOrderResponseDTO>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
return response;
}
throw new Exception("order not inserted check the data.");
}
My C# Code using built in WebRequest also returns same html :
public string Test(string url, CreateOrderDTO order)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + _accessToken);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(new JavaScriptSerializer().Serialize(order));
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
Can anyone advise what I missed here ?
In postman, the solution is turning off redirects, like on the image below:
After some tries I found that PayU rest api returns 302 (found) also ResponseUri not OK 200 as expected.
by default rest client automatically redirect to this url so I received the html content of the payment page.
The solution is :
client.FollowRedirects = false;
Hope this useful to anyone.
Also, I would like to add that the above answer by Mohammad is correct as to get the response URL we need to set AllowAutoRedirect to false. I have been trying to implement PayU LatAM WebCheckout in a console app and I was facing similar issue. I got some inspiration from the answer given here: How to get Location header with WebClient after POST request
Based on the answer, I wrote a sample code:
public class NoRedirectWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var temp = base.GetWebRequest(address) as HttpWebRequest;
temp.AllowAutoRedirect = false;
return temp;
}
}
After creating the above class, I wrote the following code in my Main method:
var request = MakeRequestLocation(new NoRedirectWebClient());
var psi = new ProcessStartInfo("chrome.exe");
psi.Arguments = request.ResponseHeaders["Location"];
Process.Start(psi);
I am now calling the function MakeRequestLocation inside the same class.
private static WebClient MakeRequestLocation(WebClient webClient)
{
var loginUrl = #"https://sandbox.checkout.payulatam.com/ppp-web-gateway-payu/";
NameValueCollection formData = new NameValueCollection
{
{"ApiKey", "4Vj8eK4rloUd272L48hsrarnUA" },
{"merchantId", "508029" },
{"accountId", "512321" },
{"description", "Test PAYU" },
{"referenceCode", "SomeRandomReferenceCode" },
{"amount", "2" },
{"tax", "0" },
{"taxReturnBase", "0" },
{"currency", "USD" },
{"signature", "Signature generated via MD5 sum" },
{"buyerFullName", "test" },
{"buyerEmail", "test#test.com" },
{"responseUrl", #"http://www.test.com/response" },
{"confirmationUrl", #"http://www.test.com/confirmation" }
};
webClient.UploadValues(loginUrl, "POST", formData);
return webClient;
}
The object that is returned by the above function contains a header called location. The value of the location is your required URL for webcheckout.

How to pass in a json 'string' array to a php page using c#, which in turn should give me back a response?

I'm a bit clueless on this so please excuse my lack of code examples.
Basically I've got a requirement to pass in a json 'string' array to a php page which in turn should give me back a response.
so firstly I need to create a string and serialize (?) this into a json object and pass it to a specified url....so firstly I'm not sure that I'm going about this in the correct way and then pass this to a URL:
protected void cmdConnect_Click(object sender, EventArgs e)
{
var sig = FormsAuthentication.HashPasswordForStoringInConfigFile(DateTime.Now.ToString("yyyy-MM-dd") + "!Cv*z]&z7:c,+zW", "SHA1");
var model = "Array (shortened for ease))";
var json = JsonConvert.SerializeObject(model);
string data = HttpUtility.UrlEncode(json);
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(data);
curlPost(data);
//jsonString.Text = json;
}
protected void curlPost(string data)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dev.com/shopping_cart.php");
request.Method = "POST";
request.ContentType = "application/json";
byte[] buffer = UTF8Encoding.UTF8.GetBytes(data);
request.ContentLength = buffer.Length;
using (Stream oStream = request.GetRequestStream())
{
oStream.Write(buffer, 0, buffer.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string myResponse = reader.ReadToEnd();
jsonString.Text = myResponse;
}
}
But although I'm getting a response (myResponse) the data that I'm passing in has no impact on it so I'm thinking that I'm either not constructing it properly or I'm not passing it in at all. What I should get back is a 'key' but what I'm actually getting back is the HTML for the php page.
I know that this is really vague but a) this is all brand new to me and b) as such I'm not sure that of the terminology involved.
Any pointers would be greatly appreciated.
Thanks,
Craig

Pass POST variables with Windows Phone App

I'm trying to insert Data from a Windows Phone App into a Database using a php script.
This is my C# code I execute when clicking on a button.
var request = WebRequest.Create(new Uri("xxx/Insert.php")) as HttpWebRequest;
request.Method = "POST";
string postdata = "Title=test&CategoryID=1";
byte[] data = Encoding.UTF8.GetBytes(postdata);
using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, request))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
I get the variable in the php script with
<?php
$title = $_POST["Title"];
$categoryID = $_POST["CategoryID"];
...
?>
Someone had the same problem here, but the solution didn't work, because
1.) WebClient is not available for WP8
2.) The second solution throws an Exception in App.i.g.cs at the line global::System.Diagnostics.Debugger.Break()
The problem is simply nothing happens. Has anybody encountered with the same problem?
I solved the Problem using System.Net.Http.HttpClient and System.Net.Http.FormUrlEncodedContent.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("baseUrl.net");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("Title", "test")
});
var result = await client.PostAsync("/insert.php", content);
string resultContent = "result: "+result.Content.ReadAsStringAsync().Result;
EDIT: awaiting the PostAsync of the client

How to access data sent from HttpWebRequest Stream via window.location.href in Java Script

I am relatively new to web programming.
I have a windows form trying to communicate with a web service through ajax and java scripts.
My form has below code,
string sURL = <<URL>>;
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(sURL);
//Modify request properties
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
request.AllowWriteStreamBuffering = false;
string sRequestData = JsonConvert.SerializeObject(new GetSessionInfo() { UserName = "xxxxxx", Database = "xxxxxx", Module = "xxxxxx" }.ToString());
StreamWriter sWriter = new StreamWriter(request.GetRequestStream());
sWriter.Write(sRequestData);
sWriter.Close();
try
{
//Extract the response
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response == null)
return false;
StreamReader responcestream = new StreamReader(response.GetResponseStream());
string ResponseData = responcestream.ReadToEnd();
responcestream.Close();
return true;
}
catch
{
throw;
}
My index.html file looks like below
function Session()
{
$.ajax({
type: "POST",
url: "/ProcessRequestFromEasyOrder",
data : JSON.stringify({ user:"****", Database:"****", module:"****"}),
contentType: "application/json; charset=utf-8",
dataType: "application/json",
async: true,
cache: false,
cors: true,
success:function(data){
alert(data);
}
});
}
At the moment I am able to call web service methods by hard coding parameters through browser. However when I try to do it via my windows form it always return me (405)Method Not Allowed.
Can someone please help me answer following questions,
Can this be achieve? if so can you provide an example which achieve
this?
Is it due to an issue with web service settings? if so how do
I get it fixed?
Any alternative ways to do this? an example would
be great
I am on .NET 4.5
Thank you very much for your help!

POSTing JSON to URL via WebClient in C#

I have some JavaScript code that I need to convert to C#. My JavaScript code POSTs some JSON to a web service that's been created. This JavaScript code works fine and looks like the following:
var vm = { k: "1", a: "2", c: "3", v: "4" };
$.ajax({
url: "http://www.mysite.com/1.0/service/action",
type: "POST",
data: JSON.stringify(vm),
contentType: "application/json;charset=utf-8",
success: action_Succeeded,
error: action_Failed
});
function action_Succeeded(r) {
console.log(r);
}
function log_Failed(r1, r2, r3) {
alert("fail");
}
I'm trying to figure out how to convert this to C#. My app is using .NET 2.0. From what I can tell, I need to do something like the following:
using (WebClient client = new WebClient())
{
string json = "?";
client.UploadString("http://www.mysite.com/1.0/service/action", json);
}
I'm a little stuck at this point. I'm not sure what json should look like. I'm not sure if I need to set the content type. If I do, I'm not sure how to do that. I also saw UploadData. So, I'm not sure if I'm even using the right method. In a sense, the serialization of my data is my problem.
Can someone tell me what I'm missing here?
Thank you!
The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:
var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");
PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.
The following example demonstrates how to POST a JSON via WebClient.UploadString Method:
var vm = new { k = "1", a = "2", c = "3", v= "4" };
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
You need a json serializer to parse your content, probably you already have it,
for your initial question on how to make a request, this might be an idea:
var baseAddress = "http://www.example.com/1.0/service/action";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
hope it helps,

Categories

Resources