I need to be able to append an encoded object to a URI to pass it to a Web API endpoint.
In this post, the author is creating an object:
var request = new Object();
request.SearchWindowStart = start.toISOString();
request.SearchWindowEnd = end.toISOString();
request.ServiceId = "5f3b6e7f-48c0-e511-80d7-d89d67631c44";
request.Direction = '0';
request.NumberOfResults = 10;
request.UserTimeZoneCode = 1;
Then they are appending it to a URL:
var req = new XMLHttpRequest()
req.open("GET", clientUrl + "/api/data/v8.0/Search(AppointmentRequest=#request)?#request=" + JSON.stringify(request) , true);
I actually cannot modify the C sharp code however I have two options. The first option is to add the parameters into the URL I actually cannot modify the c# code however I have two options. The first option is to add the parameters into the URL and the other option would be to add a body to the request with my intended object.
If I know the structure of the object ahead of time how do I include it with my request?
You can do it in a two ways.
Just add every propery of the object with the value to the url eg. /search?property1=value1&property2=value2
Of course each value should be url encoded.
Serialize the whole object into json and send it via post or get. Look at the https://www.newtonsoft.com/json how to do it. Sending request could be done by simple WebClient class.
Based on the code snippet you need to serialize the object to JSON. You can use Json.Net as already linked in the other answer.
Using OP as an example...
var request = new {
SearchWindowStart = "some_start_value",
SearchWindowEnd = "some_end_value",
ServiceId = "5f3b6e7f-48c0-e511-80d7-d89d67631c44",
Direction = '0',
NumberOfResults = 10,
UserTimeZoneCode = 1
};
//JSON.stringify(request)
var json = JsonConvert.SerializeObject(request);
var url = clientUrl + "/api/data/v8.0/Search(AppointmentRequest=#request)?#request=" + json;
From there you should be able to use the URL as desired.
let encodedObj = encodeURIComponent(JSON.stringify(yourObject))
Then you could just.
req.open("GET", clientUrl +
"/api/data/v8.0/Search(AppointmentRequest=#request)?#request=" + encodedObj, true);
Although according to: https://javascript.info/url
The encode functions are based on the obsolete version RFC2396, and advises you to use these classes instead:
URL and URLSearchParams to build a URL.
Related
I am currently building a web application that interacts with the Twitter Search API and returns tweets based on input. I am getting data returned to me, but it is coming in such a way that I do not know what to do with it. Can somebody suggest an improvement or how I can handle this data so I can format the results?
Here is the code:
public ActionResult SearchTwitter(string authenticationCode, TwitterSearch twitterSearch) //TwitterSearch holds information needed to build the URL
{
string url = BuildURL(twitterSearch);
var gettimeline = WebRequest.Create(url) as HttpWebRequest;
gettimeline.Method = "GET";
gettimeline.ContentType = "application/x-www-form-urlencoded";
gettimeline.Headers[HttpRequestHeader.Authorization] = "Bearer " + authenticationCode;
JsonResult result = new JsonResult();
try
{
var respbody = ""; //used to be string
using (var resp = gettimeline.GetResponse().GetResponseStream())//there request sends
{
var respR = new StreamReader(resp);
respbody = respR.ReadToEnd();
}
result = Json(respbody);
}
This is the trouble spot, everything else is fine (such as the catch and return statement at the end).
I am not sure where to go to effectively parse this data, as the JsonResult.Data object is a string, which isn't helpful in this situation.
Let me know if you need any more clarification.
You can use Json.net, like this:
var respbody = ""; //used to be string
using (var resp = gettimeline.GetResponse().GetResponseStream())//there request sends
{
var respR = new StreamReader(resp);
respbody = respR.ReadToEnd();
JObject timeline = JObject.Parse(respbody);
// use the docs at Newtonsoft.com to figure out how to read timeline
}
Notice that I added JObject.Parse(respbody), which gives you a JObject containing the parsed JSON data. The documentation at Newtonsoft.com is pretty decent and shouldn't take much time to work through to figure out the rest.
You can install the Newtonsoft.Json package from NuGet. Alternatively, you might also consider a 3rd party library, like LINQ to Twitter (which I wrote), to make this even easier.
I need to pass one of parameters to HttpRequest (POST).
Lets say we have 'someParam' parameter and we need to pass 'some+value' value.
When using request.AddParameter("someParam", "some+value"); - value is automatically converted to 'some%2Bvalue' and in request it looks like 'someparam=some%2Bvalue'. But the application only understands +.
Is there any way how to add parameter to request but don't encode it???
On server side should be 'some%2Bvalue' decoded to "some+value". If it is not, better solution for you is to separate values to:
request.AddParameter("someParam", "some");
request.AddParameter("someParamValue", "value");
And on server side just parse parameters to some+value as you wanted.
Another workaround would be to replace string "%2" with "+". But still it is better approach to separate values.
Possible workaround for GET:
string resource = "something";
var client = new RestClient(baseurl+ resource +"?"+"someParam"+"="+"some+value");
var request = new RestRequest(resource, method);
IRestResponse<T> response = client.Execute<T>(request);
return response.Data;
So you have to compose url by yourself and provide it whole to request.
You can use:
System.Web.HttpUtility.UrlDecode
for example:
var url = getUrlFromConfig();
var params = HttpUtility.UrlDecode("$foo/bar?someParam={some}&someParamValue={value}");
var client = new RestClient(apiUrl + params);
This will generate a valid url without your problem.
I am looking for a way to access the serialized result of the AddBody call.
I am using the built in RestSharp Serializer.
Example:
class Foo
{
public string FooField;
}
void SendRecord()
{
var f = new Foo();
f.FooField = "My Value";
request.AddBody(f);
// How do I get the serialized json result of the add body call without
// data? I would like to log the serialized output of the add body call to
// the database.
//Expected {"FooField":"My Value"}
var response = client.Execute(request);
}
I figured it out by finding this post.
request.Parameters.Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault();
I also struggled with this (using v107 preview) and couldn't find any examples of logging the actual string sent to the server. The issue I was trying to debug was getting the right serialisation settings so the object was no use to me.
The only way I could find to get the serialized body as a string was to hook into the OnBeforeRequest event on the RestRequest:
var request = new RestRequest("/", Method.Post)
.AddHeader(KnownHeaders.ContentType, "application/json", false)
.AddJsonBody(myObj);
request.OnBeforeRequest = async (httpRequest) =>
{
var requestBodyStr = await httpRequest.Content.ReadAsStringAsync();
Trace.WriteLine($"Request body: {requestBodyStr}");
};
RestSharp itself doesn't expose the serialized request body when you pass an object to it.
There is a way to get at it though, I just posted over here:
https://stackoverflow.com/a/75537611/2509281
Right off the RestSharp homepage (http://restsharp.org/):
// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string <~~~~~~~~~~
I am trying to use Plivo to send text messages from within my WindowsStore Application. Here is what almost works:
// These first 3 lines don't do what I want
var unamepass = AuthID + ":" + AuthToken;
var auth = new HttpCredentialsHeaderValue("Basic", unamepass);
httpClient.DefaultRequestHeaders.Authorization = auth;
string textBody = "sample message";
var plivoText = new
{
src = plivoNumber,
dst = phoneNumber,
text = textBody
};
string Serial = JsonConvert.SerializeObject(plivoText);
IHttpContent PlivoJsonContent = new HttpJsonContent(JsonValue.Parse(Serial));
HttpResponseMessage PlivoResponse =
await httpClient.PostAsync(
new Uri("https://api.plivo.com/v1/Account/<AuthID>/Message/")
, PlivoJsonContent);
Now, this code works... technically. I get a 202 response back. However, before it sends the text, a large authentication pops onto the screen.
If I enter the correct data I get a 202 and the text sends, otherwise I can't send the data. I want to know how to programmatically add this to the request, so I don't have to do it manually. I'm pretty sure it has something to do with the first 3 lines of the snippet, but the documentation I found online wasn't very helpful to me. I can't use RestSharp because it isn't supported for windows store projects, so I would prefer an HttpClient solution.
What "scheme" does Plivo use? How should I construct HttpCredentialsHeaderValue? Is the 3rd line correct?
The answer was startlingly simple. You must convert the string to base64 in order to send it to the header.
See: Convert UTF-8 to base64 string
I am working in calling PHP API from c#. But, my problem arise when I have to pass associative array to API. I don't know exact implementation of PHP associative array in C# but I have used dictionary. It didn't works.
I have been using RestSharp to call API.
Code Implemenation:
var client = new RestClient(BaseUrl);
var request = new RestRequest(ResourceUrl, Method.POST);
IDictionary<string,string> dicRequeset = new Dictionary<string, string>
{
{"request-id", "1234"},
{"hardware-id", "CCCCXXX"},
};
request.AddParameter("request", dicRequeset);
var response = client.Execute(request);
var content = response.Content;
PHP API Implementation(Short):
* Expected input:
* string request[request-id,hardware-id]
* Return:
* code = 0 for success
* string activation_code
*/
function activate()
{
$license = $this->checkFetchLicense();
if (!$license instanceof License) return;
$response = $license->activate((array)$this->_request->getParam('request'));
}
Can someone help me to pass array to PHP API from C#?
Maybe adding the pairs makes differences in conventions in C# and PHP? Have you tried using Add?
IDictionary<string,string> dicRequeset = new Dictionary<string, string>();
dicRequeset.Add("request-id", "1234");
dicRequeset.Add("hardware-id", "CCCCXXX");
Or using indexer?
dicRequeset["request-id"] = "1234";
dicRequeset["hardware-id"] = "CCCXXX";
Or the best I can imagine is JSON as it is designed for the purpose of transmission.
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new {request-id = "1234", hardware-id = "CCCXXX"});
The problem in the third variant despite I marked it as the best, might be that the PHP API may not decode the JSON string, because it might not be designed that way. But in general purpose JSON is meant to solve that kind of problems.
Though late post but I've solved this problem by using following approach :
var request = new RestRequest(ResourceUrl, Method.POST);
request.AddParameter("request[request-id]", hardwareId);
request.AddParameter("request[hardware-id]", hardwareId);
if I guess right, the AddParameter method of RestSharp doesn't automatically serialize an object to json thus insteadly just calls the object's toString method.
So try to get a JSON.net library and make the json encoding manually,
IDictionary<string,string> dicRequeset = new Dictionary<string, string>
{
{"request-id", "1234"},
{"hardware-id", "CCCCXXX"},
};
var jsonstr = JsonConvert.SerializeObject(dicRequeset);
request.AddParameter("request", jsonstr);
this should work.