2010-07-19 19 views
36

Ho bisogno di chiamare un metodo da un webservice, quindi ho scritto questo codice:Come aggiungere parametri in una richiesta Web?

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(); 

Ma questo metodo richiede alcuni parametri, come segue: i dati

Messaggio:

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

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

Come posso aggiungere questi parametri a questo WebRequest?

Grazie in anticipo.

risposta

29

Se questi sono i parametri di url-string, allora avete bisogno di aggiungere loro attraverso '?' e caratteri "&", ad esempio http://example.com/index.aspx?username=Api_user&password=Api_password.

Se questi sono i parametri di richiesta POST, quindi è necessario creare i dati POST e scrivere per richiedere flusso. Qui è il metodo di campionamento:

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; 
     } 
+0

@Omid un numero che indica quanto tempo il sistema deve attendere prima di rinunciare. – RyanfaeScotland

+1

Sembra contorto rispetto alla risposta di @ CoderHawk. – Kehlan

+0

vecchio argomento ma .. cos'è "Costante"? –

68

Usa flusso di scrivere contenuti di 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(); 
+0

quali sono i parametri extra aggiunti a questo newStream.Write '(dati, 0, data.Length)' – Smith

+0

@Smith - username e password, vedere la prima linea – CoderHawk

+0

bel @CoderHawk .. grazie a migliori pratiche di codifica – KingRider

8

Per fare messaggi FORM, il modo migliore è quello di utilizzare WebClient.UploadValues ​​() con un metodo POST.

4

Spero che questo funziona

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