Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient- adding parameters to Get request

Tags:

c#

restsharp

I have a RestRequest which I am trying to convert to HttpClient Get request. Is there any way I can send parameters the way it is done below?

private readonly IRestClient _restClient;
public Type GetInfo(string name)
{
    var request = new RestRequest(url, Method.GET);
    request.AddParameter("name", "ivar");
    var response = _restClient.ExecuteRequest(request);
    return ExecuteRequest<Type>(request);
}
like image 808
legend Avatar asked Jan 20 '16 00:01

legend


People also ask

How do you add parameters in GET request?

To do http get request with parameters in Angular, we can make use of params options argument in HttpClient. get() method. Using the params property we can pass parameters to the HTTP get request. Either we can pass HttpParams or an object which contains key value pairs of parameters.

How send parameters in HTTP GET request?

When the GET request method is used, if a client uses the HTTP protocol on a web server to request a certain resource, the client sends the server certain GET parameters through the requested URL. These parameters are pairs of names and their corresponding values, so-called name-value pairs.

How do I set parameters in HttpPost?

just type your param name and value like : debug_data=1 or username_hash=jhjahbkzjxcjkahcjkzhbcjkzhbxcjshd I'm using this code with params and there is no problem for me. without annotations is the values are also null. So the problem should be in your code and the way you put the values.


1 Answers

If I recall correctly, RestSharp's AddParameter method doesn't add request headers but rather add Uri arguments for GET or request body parameters for POST.

There is no analogous method for HttpClient so you need to format the Uri for a GET request yourself.

Here's a method I find handy that will take a dictionary of string/object pairs and format a Uri query string.

public static string AsQueryString(this IEnumerable<KeyValuePair<string, object>> parameters)
{
    if (!parameters.Any())
        return "";

    var builder = new StringBuilder("?");

    var separator = "";
    foreach (var kvp in parameters.Where(kvp => kvp.Value != null))
    {
        builder.AppendFormat("{0}{1}={2}", separator, WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value.ToString()));

        separator = "&";
    }

    return builder.ToString();
}
like image 106
dkackman Avatar answered Oct 13 '22 06:10

dkackman