Post method for HTTP Handler - c#

I have a handler. When I call it with URL that is to say GET method, it works because I get values with my below handler code.
var encodedUrl = HttpUtility.UrlEncode(context.Request.QueryString.ToString());
How can I get values when I use post method which is below from Handler side:
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["a"] = "a";
data["b"] = "b";
var response = wb.UploadValues("http://localhost:126/Web", "POST", data);
}

When you receive an http response you basically depend on the "Content Type". Depending on this type is that you read it.
Here is a reference on this topic:
http://msdn.microsoft.com/en-us/library/ms525208(v=vs.90).aspx
For instance if you decide to receive an "application/json" response type. You may be able to use this:
Using WebClient for JSON Serialization?
From I can see in your sample it looks like you are trying to implement an "application/x-www-form-urlencoded" and the post needs to be formatted accordingly. Here is a sample for that:
http://msdn.microsoft.com/en-us/library/system.net.webclient.headers(v=vs.110).aspx
How are parameters sent in an HTTP POST request?
But there are other options available. I hope this is the answer you were looking for.

Related

What is the idiomatic way to make a get request using RestSharp?

I'm trying to make a GET request to a REST api which returns a JSON. This is what I have right now:
RestClient client = new RestClient(BASE_URL);
var request = new RestRequest(CONTROLLER_PATH);
var response = await client.GetAsync<MyDtoClass[]>(request);
When this code executes, response is an array of MyDtoClass but the fields in each element of the array are null. If instead, I run this code (I removed the generic):
RestClient client = new RestClient(BASE_URL);
var request = new RestRequest(CONTROLLER_PATH);
var response = await client.GetAsync(request);
then response is a string represintation of the JSON that BASE_URL + CONTROLLER_PATH returns (nothing is null).
What is the idiomatic way to make a request to this REST api and convert the response into an array of MyDtoClass. Also, if anyone has suggestions for a library you think is better then RestSharp, please share.
Thank you in advance.
The issue was that MyDtoClass had fields instead of properties.

POST json to another url

I've a problem as I need to send some json to a url. When I send all my json and token to the page.
Then there will be no content JSON value into the system.
I have checked up on whether there is some content and it is there, but it sends just do not like json values.
string apiKeyToken = model.reepaytoken; // TOKEN HERE.
string URLLink = APIClassPay.HelperPay.CreateCustomerURL;//URL to send it json to.
WebClient client = new WebClient();
//JSON coming here!
var JSONCustomer = APIClassPay.HelperPay.CreateCustomer(model.Brugernavn, model.Adresse, model.Byen, model.Postnr.ToString(), model.Mobil.ToString(), model.Fornavn, model.Efternavn);
client.Headers.Add("text/json", JSONCustomer);
client.Headers.Set("X-Auth-Token", apiKeyToken);
string reply = client.DownloadString(URLLink);
When I blow my json looks like this.
[HttpPost]
public ActionResult information(BuyMedlemskabViewModel model)
{
DataLinqDB db = new DataLinqDB();
var Pric = db.PriceValues.FirstOrDefault(i => i.id == model.HiddenIdMedlemskab);
if (Pric != null)
{
string _OrderValue = DateTime.Now.Year + Helper.Settings.PlanValue();
Session[HelperTextClass.HelperText.SessionName.OrderId] = _OrderValue;
Session[HelperTextClass.HelperText.SessionName.FakturaId] = model.HiddenIdMedlemskab;
Session[HelperTextClass.HelperText.SessionName.fornavn] = model.Fornavn;
Session[HelperTextClass.HelperText.SessionName.efternavn] = model.Efternavn;
Session[HelperTextClass.HelperText.SessionName.Adresse] = model.Adresse;
Session[HelperTextClass.HelperText.SessionName.Post] = model.Postnr;
Session[HelperTextClass.HelperText.SessionName.Byen] = model.Byen;
Session[HelperTextClass.HelperText.SessionName.Mobil] = model.Mobil;
string apiKeyToken = model.reepaytoken;.
string URLLink = APIClassPay.HelperPay.CreateCustomerURL;//URL to send it json to.
WebClient client = new WebClient();
//JSON coming here!
var JSONCustomer = APIClassPay.HelperPay.CreateCustomer(model.Brugernavn, model.Adresse, model.Byen, model.Postnr.ToString(), model.Mobil.ToString(), model.Fornavn, model.Efternavn);
client.Headers.Add("text/json", JSONCustomer);
client.Headers.Set("X-Auth-Token", apiKeyToken);
string reply = client.DownloadString(URLLink);
}
return RedirectToAction("information");
}
EDIT - Update (ERROR HERE):
ReePay API reference: https://docs.reepay.com/api/
I think there are a few things, you'll have to fix:
First of all you're obviously trying to create a ressource (usually a POST or PUT, speaking in REST-words but you're using WebClient's DownloadString-method which performs a GET. So I think you should probably use a POST or PUT instead but which one to chose exactly depends on the web service you're contacting.
Then you seem to have mistaken the Content-Type-header and tried to pack the payload in there. The payload - your customer JSON - will have to be put into the request's body.
Based on your previous questions I assume the service you're trying to contact is either PayPal or QuickPay. To further help you with this question, it'd be helpful if you could specify which one you use.
If it's QuickPay, please notice that there's an official .NET client which you could use instead of using WebClient on you own.
But anyway for making HTTP requests I'd suggest you to use HttpClient in favor of WebClient. You'd generally do it in a way like this:
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post,
APIClassPay.HelperPay.CreateCustomerURL);
request.Headers.Add("X-Auth-Token", apiKeyToken);
request.Headers.Add("Content-Type", "application/json");
request.Content = new StringContent(JSONCustomer);
var response = await httpClient.SendAsync(request);
}
EDIT:
As you clarified in a comment, the service you're using is Reepay. If you take a look at the documentation of the create customer method, you can see, that the necessary HTTP method is POST. So the code snippet above should generally fit.
Regarding the compilation error you faced, I updated the code-snipped above. There was a mistake in the variable names I chose. Please note, that you dropped the keyword await as I can see from your screenshot. Please re-enter it. If the compiler complains about it, it's very likely that the .NET framework version of your project is less than 4.5 which is necessary to use async/await.
So you should update your project's .NET framework version at best to version 4.6.1 as Microsoft recently announced that support for 4.5 and others is discontinued. Have a look here on how to do that.

How do I get the destination URL of a shortened URL?

I have an API (https://www.readability.com/developers/api/parser#idm386426118064) to extract the contents of the webapges, but on passing a shortened url or an url that redirects to other, it gives error.
I am developing windows phone 8.1 (xaml) app. Is there any way to get the destination url in c# or any work around?
eg url - http://www.bing.com/r/2/BB7Q4J4?a=1&m=EN-IN
You could intercept the Location header value before the HttpClient follows it like this:
using (var handler = new HttpClientHandler())
{
handler.AllowAutoRedirect = false;
using (var client = new HttpClient(handler))
{
var response = await client.GetAsync("shortUrl");
var longUrl = response.Headers.Location.ToString();
}
}
This solution will always be the most efficient because it only issue one request.
It is possible however, that the short url will reference another short url and consequently cause this method to fail.
An alternative solution would be to allow the HttpClient to follow the Location header value and observe the destination:
using (var client = new HttpClient())
{
var response = client.GetAsync("shortUrl").Result;
var longUrl = response.RequestMessage.RequestUri;
}
This method is both terser and more reliable than the first.
The drawback is that this code will issue two requests instead of one.
You can get the ResponseUri from GetResponse():
string redirectedURL = WebRequest.Create("http://www.bing.com/r/2/BB7Q4J4?a=1&m=EN-IN")
.GetResponse()
.ResponseUri
.ToString();
Interesting article, by the way.
You need to inspect the headers returned from the URL.
If you get HTTP return codes 301 or 302, then you are being notified that the page is redirecting you to another URL.
See http://www.w3.org/Protocols/HTTP/HTRESP.html for more details about HTTP return codes.

How to send request and get response from localhost in c#

I have installed "vivekn sentimental tool" which is running in my local host.when we send an http request using unirest post method to the server which contains a string it sends response whether it is positive or negative.I had used it in java.but anyone tell me how to use that in c#
here is my java code
HttpResponse request = Unirest.post("http:localhost:1681/api/text/")
.header("X-Mashape-Authorization", "xxxxxxxxxx")
.field("txt", "i like icecream").asJson();
JSONObject js = new JSONObject(request.getBody().toString());
Object ob = js.get("result");
JSONObject job = new JSONObject(ob.ToString);
String sentiment = (String)job.get("sentiment");
what I need is I want to send a request to the localhost and receive a response which is json with or without using unirest
It's going to roughly look something like this:
using (var wc = new WebClient())
{
wc.Headers.Add(
"X-Mashape-Authorization", "1R1tvmPFLFL7brrvfO9jvsqnvhiVggAn");
var body = wc.DownloadString("http:localhost:1681/api/text/");
var js = Newtonsoft.Json.Linq.JObject.Parse(body);
/* do something with the json */
}
You'll need to get the Newtonsoft library from NuGet - ID: "Newtonsoft.Json".

HTTP POST with JSON object returned c#

I am trying to create a HTTP Post that returns a JSON object with 2 attributes.
Details are below:
HTTP POST to http://text-processing.com/api/sentiment/ with form encoded data which contains a string. A JSON object response with 2 attributes is retuned; lable and negative.
I am tying to do this in c#, which is where I am struggling.
Thank you
You can try using a WebClient like this
WebClient webclient = new WebClient();
NameValueCollection postValues = new NameValueCollection();
postValues.Add("foo", "fooValue");
postValues.Add("bar", "barValue");
byte[] responseArray = webclient.UploadValues(*url*, postValues);
string returnValue = Encoding.ASCII.GetString(responseArray);
MSDN page also has an example.

Categories

Resources