I'm having difficulty putting together a request by sending a json content, can not find anything in the 4.x documentation it's completely different from version 3.x
RestClient client = new RestClient();
client.Host = "localhost";
client.Port = 8080;
RestRequest request = new Grapevine.Client.RestRequest("/route1");
request.HttpMethod = HttpMethod.POST;
RestResponse response = client.Execute(request) as RestResponse;
Somewhere in your code - prior to sending your request - you need to set the body (or payload) of your request.
request.Payload = "send this data";
The payload is just a string, so it's up to you to serialize your objects to a JSON string before making the assignment (and set the ContentType property appropriately). The Json.NET library is widely used to accomplish this. You can also do this by hand:
request.ContentType = ContentType.JSON;
request.Payload = "{\"key\":\"value\"}";
Related
Hi I'm new with moodle and I'm getting an error when calling the webservice.
Currently I'm trying to retrieve a user from moodle with the following function core_user_get_users_by_field and I'm using rest service to do so. I already managed to create a user thus I am authenticated to use the service.
the error that I'm receiving is
Missing required key in single structure: field
The bellow is the code was used to create a User. the issue that I got from the error is that the parameter that I need to send for the post is not formatted well. Does anyone know how to search correctly with this method or any other method.
String token = "token";
String postData = "username=username";
string createRequest = string.Format("http://domain/webservice/rest/server.php?wstoken={0}&wsfunction={1}&moodlewsrestformat=json", token, "core_user_get_users_by_field");
// Call Moodle REST Service
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(createRequest);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// Encode the parameters as form data:
byte[] formData =
UTF8Encoding.UTF8.GetBytes(postData);
req.ContentLength = formData.Length;
// Write out the form Data to the request:
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
// Get the Response
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string contents = reader.ReadToEnd();
// Deserialize
JavaScriptSerializer serializer = new JavaScriptSerializer();
if (contents.Contains("exception"))
{
// Error
MoodleException moodleError = serializer.Deserialize<MoodleException>(contents);
}
else
{
// Good
}
The webservice core_user_get_users_by_field needs an associative array given as parameter with the following key:values
'field': 'id'
'values': array of integers (must be an array, possibly with just one value)
In PHP it would be, for example:
$parameters = array('field' => 'id', 'values' => array(13));
It means: the user whose 'id' has the value of 13. Of course, you can use other parameters as well: ('field'=>'lastname', 'values'=> array('Smith'))
The parameters you can choose are the fields of the Moodle 'user' table.
Try to build these parameters in your postData variable.
Here's URL that work with my put this url in postman and set http method to post method
hostname/webservice/rest/server.php?wstoken=any_token&wsfunction=core_user_get_users_by_field&field=email&values[0]=h#fci.com
&moodlewsrestformat=json
This is a good way to grab the request before the response: useragent = getHttpRequestData().headers["User-Agent"];
What I noticed is that it will not grab the request unless it is on the actual list of header request. An example is I that it seems to only pull the basic request data. For instance if I set the cache control in the web.config file it does set cache, max age and etag, but when setting etags = getHttpRequestData().headers["ETag"]; and trying to output the data for the ETag generated by the web.config file/server it will not grab the ETag data to output. A few others that I tested are:
useragent = getHttpRequestData().headers["User-Agent"];
acceptencoding = getHttpRequestData().headers["Accept-Encoding"];
acceptlanugage = getHttpRequestData().headers["Accept-Language"];
cachecontrol = getHttpRequestData().headers["Cache-Control"];
connection = getHttpRequestData().headers["Connection"];
accept = getHttpRequestData().headers['Accept'];
contentlength = getHttpRequestData().headers['Content-Length'];
Request data is sent from the browser. You can see that with ColdFusion. But IIS sets response headers (such as etag) after ColdFusion is done processing. It's a response not a request. You cannot see that with ColdFusion, but you can in your browser. EX:
if I do a simple HTTP GET request with e.g. POSTMAN then in the response there's an element called 'entity_id'.
e.g. https://www.facebook.com/yourFacebookName
If however, I do the request from a simple C# app then the following code doesnt return the 'entity_id' element in the response and I cant figure out why?
Code from app:
string html = string.Empty;
string url = string.Format("https://www.facebook.com/{0}", "yourFBName");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
if (html.Contains("entity_id"))
{
//do some stuff
}
Anyone know why its dropping the 'entity_id' element, but returning it when hitting that url from POSTMAN etc?
As i am either too dump to find the proper answer or it is simply not out there ... how the hek i replace the "outdated" WebRequest properly with the HttpClient "replacement"?
In the WebRequest i tendet to serialize & analyze the actual cookie as the webpage returns a partial JSON cookie ... however ... i still did not found a way to get a proper CookieContainer (or whatever form of cookie) from the frking HttpClient ... also ... every google request leads me to 20000000 years old answers or outdated documents (+ some upToDate docs which all just refer to "GET" requests without any cookies involved -.-*))
would be kindfull if somebody could lead me to the correct path ...
thx
greets
X39
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient();
client.DefaultRequestHeaders.UserAgent.TryParseAdd(app.Settings.UserAgent);
var response = await client.PostAsync(new Uri(app.Settings.Pr0grammUrl.Api + "user/login"), new Windows.Web.Http.HttpStringContent(postDataBuilder.ToString()));
By default, HttpClient handles cookies by itself through the default HttpBaseProtocolFilter. You can get cookies associated with a URI through GetCookies method of the HttpCookieManager class:
Gets an HttpCookieCollection that contains the HttpCookie instances
that are associated with a specific URI.
using (var protocolFilter = new HttpBaseProtocolFilter()) {
var cookieManager = protocolFilter.CookieManager;
var cookies = cookieManager.GetCookies(uri);
foreach (var cookie in cookies) {
// Here is each cookie
}
}
You should also be able to set/get cookies through HTTP request and response headers. To disallow HttpClient from handling cookies by itself, create an instance of HttpBaseProtocolFilter and set the CookieUsageBehavior to HttpCookieUsageBehavior.NoCookies:
NoCookies: Do not handle cookies automatically.
// Create http filter
httpFilter = new HttpBaseProtocolFilter();
httpFilter.CookieUsageBehavior = HttpCookieUsageBehavior.NoCookies;
// Create http client
httpClient = new HttpClient(httpFilter);
// Handle cookies through HTTP headers
I am working in a Windows Phone 8 PCL project. I am using a 3rd party REST API and I need to use a few HttpOnly cookies originated by the API. It seems like getting/accessing the HttpOnly cookies from HttpClientHandler's CookieContainer is not possible unless you use reflection or some other backdoor.
I need to get these cookies and send them in subsequent requests otherwise I am not going to be able to work with this API - how can I accomplish this? Here is what my current request code looks like:
Thanks in advance.
//Some request
HttpRequestMessage request = new HttpRequestMessage();
HttpClientHandler handler = new HttpClientHandler();
//Cycle through the cookie store and add existing cookies for the susbsequent request
foreach (KeyValuePair<string, Cookie> cookie in CookieManager.Instance.Cookies)
{
handler.CookieContainer.Add(request.RequestUri, new Cookie(cookie.Value.Name, cookie.Value.Value));
}
//Send the request asynchronously
HttpResponseMessage response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
//Parse all returned cookies and place in cookie store
foreach (Cookie clientcookie in handler.CookieContainer.GetCookies(request.RequestUri))
{
if (!CookieManager.Instance.Cookies.ContainsKey(clientcookie.Name))
CookieManager.Instance.Cookies.Add(clientcookie.Name, clientcookie);
else
CookieManager.Instance.Cookies[clientcookie.Name] = clientcookie;
}
HttpClient httpClient = new HttpClient(handler);
The HttpOnly cookie is inside the CookieContainer, it's only that is not exposed. If you set the same instance of that CookieContainer to the next request it will set the hidden cookie there (as long as the request is made to the same site the cookie specifies).
That solution will work until you need to serialize and deserialize the CookieContainer because you are restoring state. Once you do that you lose the HttpOnly cookies hidden inside the CookieContainer. So, a more permanent solution would be using Sockets directly for that request, read the raw request as a string, extract the cookie and set it to the next requests. Here's the code for using Sockets in Windows Phone 8:
public async Task<string> Send(Uri requestUri, string request)
{
var socket = new StreamSocket();
var hostname = new HostName(requestUri.Host);
await socket.ConnectAsync(hostname, requestUri.Port.ToString());
var writer = new DataWriter(socket.OutputStream);
writer.WriteString(request);
await writer.StoreAsync();
var reader = new DataReader(socket.InputStream)
{
InputStreamOptions = InputStreamOptions.Partial
};
var count = await reader.LoadAsync(512);
if (count > 0)
return reader.ReadString(count);
return null;
}
There is also a second possibility - to manually go through response headers, grab and then parse Set-Cookie headers using a bunch of custom code.
It looks something like that, when you are going to match and save a single PHPSESSID cookie (assume LatestResponse is your HttpResponseMessage containing website response):
if (LatestResponse.Headers.ToString().IndexOf("Set-Cookie:") != -1) try
{
string sid = LatestResponse.Headers.ToString();
sid = sid.Substring(sid.IndexOf("Set-Cookie:"), 128);
if (sid.IndexOf("PHPSESSID=") != -1)
{
settings.Values["SessionID"] = SessionID = sid.Substring(sid.IndexOf("PHPSESSID=") + 10, sid.IndexOf(';') - sid.IndexOf("PHPSESSID=") - 10);
handler.CookieContainer.Add(new Uri("http://example.com", UriKind.Absolute), new System.Net.Cookie("PHPSESSID", SessionID));
}
} catch (Exception e) {
// your exception handling
}
Note this code inserts the cookie to CookieContainer for that object's life unless manually deleted. If you want to include it in a new object, just pull the right setting value and add it to your new container.