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".
Related
I am trying to receive data back from the server using POST method and the request should have a body. I am using WebClient for this and trying to get the response back in string. I know we can use HttpClient to achieve this. But I want to use WebClient for this specific instance.
I went through this post and tried UploadString and the response gives me a 400 BAD Request.
using (var wc = new WebClient())
{
wc.Headers.Add("Accept: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
I tested the end point using Postman (with the request header having an api key and the request body in JSON) and it works fine.
I know I haven't formatted the request right. Can someone please help me.
Big Thanks to #Santiago Hernández. The issue was using wc.Headers.Add("Accept: application/json"); in the request header. Changing it to wc.Headers.Add("Content-Type: application/json"); returned a 200 Ok response. The code modification is as follows
using (var wc = new WebClient())
{
wc.Headers.Add("Content-Type: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
Accept tells the server the kind of response the client will accept and Content-type is about the payload/content of the current request or response. Do not use Content-type if the request doesn't have a payload/ body.
More information about this can be found here.
I need guidance on how I can create a POST request to a web API exposed #http://server:8100/api/SoftwareProductBuild' this API takes an XML as input, let's assume the XML is in variable XMLcontent
I have done this python as follows, how to convert to C#?
import requests
with open("PRE_COMMIT_LA.UM.5.8_524f7fef-5b37-11e7-b4ee-f0921c133f10.xml") as f:
body = f.read()
headers = {'Content-Type': 'application/xml'}
response = requests.post(
'http://ctdsapi1:8100/api/SoftwareProductBuild', data=body, headers=headers)
print "Printing DEV Pool Response\n"
print response
print "Done...Printing Dev Pool Response\n"
print response.ok
print response.content
Something like the following should get you most of the way there. Most applicable is the PostAsXmlAsync method.
// In whatever async method
// Assuming actual file? Add applicable checks as well.
var xml = File.ReadAllText(fullPath + "PRE_COMMIT_LA.UM.5.8_524f7fef-5b37-11e7-b4ee-f0921c133f10.xml");
using (var client = new System.Net.Http.HttpClient())
{
var response = await client.PostAsXmlAsync("http://ctdsapi1:8100/api/SoftwareProductBuild", xml);
if (!response.IsSuccessStatusCode)
{
throw new InvalidUriException("Some error with details."));
}
Console.WriteLine("Printing DEV Pool Response\n");
...etc.
}
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.
I've written a rudimentary API in a Flask project to allow POSTing data via JSON strings. The JSON requires two properties: username and apikey, which are validated through the following decorator:
def apikey_required(f):
#wraps(f)
def decorated_function(*args, **kwargs):
if not request.json:
abort(404)
json_data = request.json
if not 'username' in json_data or not 'apikey' in json_data:
abort(404)
user = User.query.filter(User.username == json_data['username']).first()
if not user or user.status != "superuser":
abort(404)
if not user.apikey or user.apikey != json_data['apikey']:
return jsonify({'status': 'error', 'message': 'unrecognized API key'})
return f(*args, **kwargs)
return decorated_function
I've written routes utilizing this decorator and they work beautifully in Python applications: Here's the basic structure of an API route:
#mod.route('/invadd', methods=['GET', 'POST'])
#apikey_required
def invadd():
json = request.json
#lots of application-specific logic that passes unit tests
My Flask unit tests work fine:
good_post_response = self.app.post(
'api/invadd', data=json.dumps(test_json),
content_type='application/json') # assertions which verify the reponse pass
Python applications I've written work fine:
response = urllib2.urlopen(req, json.dumps(post_json)) #req is an api route URL
response_json = json.loads(response.read())
But in my C# app, I get a SocketException: No connection could be made because the target machine actively refused it. when I try to post JSON to these same routes. Here's a relevant code snippet:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create();
request.ContentType = "application/json";
request.Method = "POST";
request.ContentLength = postJSON.Length;
using (StreamWriter sw = new StreamWriter(request.GetRequestStream())) <--- FAILURE POINT
{
sw.Write(postJSON.ToString());
sw.Flush();
sw.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string result = sr.ReadToEnd();
AddFeedback(result);
}
I've also tried using the WebClient class:
WebClient wc = new WebClient();
AddFeedback(String.Format("Processing order {0}", order.OrderID));
string postJSON = BuildJSON(order);
string url = String.Format("{0}api/invadd", gslBase); //I verified that the URL is correctly constructed
string response = wc.UploadString(url, "POST", postJSON);
AddFeedback(response);
It's clear to me that the failure happens when the app tries to initiate the connection to the route, as it never gets to the point where it's actually trying to post the JSON data. But I'm not sure how to get around this. Do I need to change my Flask route?
That kind of exception indicates that there was a error at the socket level - that's before you reach JSON, or even HTTP.
Make sure you're connecting to the right machine and the right port.
It's not clear where you're inputting that data on your C# code - you probably should be using WebRequest.Create("yoururl") .
You can also try to connect using a browser, and see if it works.
If all those details are right, you can use wireshark to check what, exactly, is causing the connection to fail
I am trying to use the Google OAuth and I have the first part done but now it want's me to POST the following:
code= client_id= client_secret= redirect_uri= grant_type=authorization_code
Currently I am trying to do:
var http = new HttpClient();
http.MaxResponseContentBufferSize = Int32.MaxValue;
var response = await http.GetStringAsync(uri);
That will send but get an error back as it's requesting I do Post sending (could use PostAsync) but I have no content to send to "POST" and it's supposed to return a JSON Feed...
Any ideas?