C# 如何使用参数发出 HTTP get 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/514892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:23:07  来源:igfitidea点击:

How to make an HTTP get request with parameters

c#httpwebrequestget

提问by CruelIO

Is it possible to pass parameters with an HTTPget request? If so, how should I then do it? I have found an HTTPpost requst (link). In that example the string postDatais sent to a webserver. I would like to do the same using getinstead. Google found this example on HTTPget here. However no parameters are sent to the web server.

是否可以通过HTTPget 请求传递参数?如果是这样,我应该怎么做?我找到了一个HTTP帖子请求(链接)。在该示例中,字符串postData被发送到网络服务器。我想使用get来做同样的事情。谷歌在HTTPget here上找到了这个例子。但是没有参数被发送到网络服务器。

采纳答案by EndangeredMassa

In a GET request, you pass parameters as part of the query string.

在 GET 请求中,您将参数作为查询字符串的一部分传递。

string url = "http://somesite.com?var=12345";

回答by Marc Gravell

First WebClientis easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:

首先WebClient是更容易使用;GET 参数在查询字符串上指定 - 唯一的技巧是记住转义任何值:

        string address = string.Format(
            "http://foobar/somepage?arg1={0}&arg2={1}",
            Uri.EscapeDataString("escape me"),
            Uri.EscapeDataString("& me !!"));
        string text;
        using (WebClient client = new WebClient())
        {
            text = client.DownloadString(address);
        }

回答by wisbucky

My preferred way is this. It handles the escaping and parsing for you.

我的首选方式是这样。它为您处理转义和解析。

WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");

回答by Cesar

The WebRequest object seems like too much work for me. I prefer to use the WebClient control.

WebRequest 对象对我来说似乎太多了。我更喜欢使用 WebClient 控件。

To use this function you just need to create two NameValueCollections holding your parameters and request headers.

要使用这个函数,你只需要创建两个 NameValueCollections 来保存你的参数和请求头。

Consider the following function:

考虑以下函数:

    private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
    {
        string ResponseText = null;
        using (WebClient client = new WebClient())
        {
            try
            {
                if (RequestHeaders != null)
                {
                    if (RequestHeaders.Count > 0)
                    {
                        foreach (string header in RequestHeaders.AllKeys)
                            client.Headers.Add(header, RequestHeaders[header]);
                    }
                }
                if (QueryStringParameters != null)
                {
                    if (QueryStringParameters.Count > 0)
                    {
                        foreach (string parm in QueryStringParameters.AllKeys)
                            client.QueryString.Add(parm, QueryStringParameters[parm]);
                    }
                }
                byte[] ResponseBytes = client.DownloadData(URL);
                ResponseText = Encoding.UTF8.GetString(ResponseBytes);
            }
            catch (WebException exception)
            {
                if (exception.Response != null)
                {
                    var responseStream = exception.Response.GetResponseStream();

                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            Response.Write(reader.ReadToEnd());
                        }
                    }
                }
            }
        }
        return ResponseText;
    }

Add your querystring parameters (if required) as a NameValueCollection like so.

添加您的查询字符串参数(如果需要)作为 NameValueCollection 像这样。

        NameValueCollection QueryStringParameters = new NameValueCollection();
        QueryStringParameters.Add("id", "123");
        QueryStringParameters.Add("category", "A");

Add your http headers (if required) as a NameValueCollection like so.

添加您的 http 标头(如果需要)作为 NameValueCollection 像这样。

        NameValueCollection RequestHttpHeaders = new NameValueCollection();
        RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");

回答by Priyanka

You can also pass value directly via URL.

您也可以直接通过 URL 传递值。

If you want to call method public static void calling(string name){....}

如果你想调用方法 public static void calling(string name){....}

then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya); webrequest.Method = "GET"; webrequest.ContentType = "application/text";

那么你应该调用使用HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya); webrequest.Method = "GET"; webrequest.ContentType = "application/text";

Just make sure you are using ?Object = valuein URL

只要确保您?Object = value在 URL中使用