简体   繁体   English

如何将参数添加到 WebRequest 中?

[英]How to add parameters into a WebRequest?

I need to call a method from a webservice, so I've written this code:我需要从网络服务调用一个方法,所以我写了这个代码:

 private string urlPath = "http://xxx.xxx.xxx/manager/";
 string request = urlPath + "index.php/org/get_org_form";
 WebRequest webRequest = WebRequest.Create(request);
 webRequest.Method = "POST";
 webRequest.ContentType = "application/x-www-form-urlencoded";
 webRequest.
 webRequest.ContentLength = 0;
 WebResponse webResponse = webRequest.GetResponse();

But this method requires some parameters, as following:但是这个方法需要一些参数,如下:

Post data:发布数据:

_username:'API USER',         // api authentication username

_password:'API PASSWORD',     // api authentication password

How can I add these parameters into this Webrequest?如何将这些参数添加到此 Webrequest 中?

Thanks in advance.提前致谢。

Use stream to write content to webrequest使用流将内容写入 webrequest

string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;  
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();  

If these are the parameters of url-string then you need to add them through '?'如果这些是 url-string 的参数,那么你需要通过 '?' 添加它们。 and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password .和 '&' 字符,例如http://example.com/index.aspx?username=Api_user&password=Api_password

If these are the parameters of POST request, then you need to create POST data and write it to request stream.如果这些是 POST 请求的参数,那么您需要创建 POST 数据并将其写入请求流。 Here is sample method:这是示例方法:

private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
                                        CookieContainer cookieContainer,
                                        string userAgent, string acceptHeaderString,
                                        string referer,
                                        string contentType, out string responseUri)
        {
            var result = "";
            if (!string.IsNullOrEmpty(requestUri))
            {
                var request = WebRequest.Create(requestUri) as HttpWebRequest;
                if (request != null)
                {
                    request.KeepAlive = true;
                    var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
                    request.CachePolicy = cachePolicy;
                    request.Expect = null;
                    if (!string.IsNullOrEmpty(method))
                        request.Method = method;
                    if (!string.IsNullOrEmpty(acceptHeaderString))
                        request.Accept = acceptHeaderString;
                    if (!string.IsNullOrEmpty(referer))
                        request.Referer = referer;
                    if (!string.IsNullOrEmpty(contentType))
                        request.ContentType = contentType;
                    if (!string.IsNullOrEmpty(userAgent))
                        request.UserAgent = userAgent;
                    if (cookieContainer != null)
                        request.CookieContainer = cookieContainer;

                    request.Timeout = Constants.RequestTimeOut;

                    if (request.Method == "POST")
                    {
                        if (postData != null)
                        {
                            request.ContentLength = postData.Length;
                            using (var dataStream = request.GetRequestStream())
                            {
                                dataStream.Write(postData, 0, postData.Length);
                            }
                        }
                    }

                    using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
                    {
                        if (httpWebResponse != null)
                        {
                            responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
                            cookieContainer.Add(httpWebResponse.Cookies);
                            using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                            {
                                result = streamReader.ReadToEnd();
                            }
                            return result;
                        }
                    }
                }
            }
            responseUri = null;
            return null;
        }

对于 FORM 帖子,最好的方法是将 WebClient.UploadValues() 与 POST 方法一起使用。

希望这有效

webRequest.Credentials= new NetworkCredential("API_User","API_Password");

I have a feeling that the username and password that you are sending should be part of the Authorization Header.我有一种感觉,您发送的用户名和密码应该是 Authorization Header 的一部分。 So the code below shows you how to create the Base64 string of the username and password.所以下面的代码向您展示了如何创建用户名和密码的 Base64 字符串。 I also included an example of sending the POST data.我还包含了一个发送 POST 数据的示例。 In my case it was a phone_number parameter.就我而言,它是一个 phone_number 参数。

string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;

string data = "phone_number=19735559042"; 
byte[] dataStream = Encoding.UTF8.GetBytes(data);

request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();

HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();

The code below differs from all other code because at the end it prints the response string in the console that the request returns.下面的代码与所有其他代码不同,因为最后它在请求返回的控制台中打印响应字符串。 I learned in previous posts that the user doesn't get the response Stream and displays it.我在之前的帖子中了解到,用户没有得到响应 Stream 并显示它。

//Visual Basic Implementation Request and Response String
  Dim params = "key1=value1&key2=value2"
    Dim byteArray = UTF8.GetBytes(params)
    Dim url = "https://okay.com"
    Dim client = WebRequest.Create(url)
    client.Method = "POST"
    client.ContentType = "application/x-www-form-urlencoded"
    client.ContentLength = byteArray.Length
    Dim stream = client.GetRequestStream()

    //sending the data
    stream.Write(byteArray, 0, byteArray.Length)
    stream.Close()

//getting the full response in a stream        
Dim response = client.GetResponse().GetResponseStream()

//reading the response 
Dim result = New StreamReader(response)

//Writes response string to Console
    Console.WriteLine(result.ReadToEnd())
    Console.ReadKey()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM