2010-05-18 16 views
18

Chcesz, aby serwer wykonał test POST dla interfejsu API, jak dodać wartości POST do obiektu WebRequest i jak wysłać go, aby uzyskać odpowiedź (będzie to ciąg znaków)?Jak używać WebRequest do POST niektórych danych i odczytu odpowiedzi?

Potrzebuję POST DWA wartości, a czasami więcej, widzę w tych przykładach, gdzie napis string postData = "ciąg do opublikowania"; ale w jaki sposób mogę pozwolić, aby to, co ZNAJDOWAŁEM, wiedzieć, że istnieje wiele wartości formularza?

+0

Przykład można znaleźć w [Dlaczego wysyłanie danych postów za pomocą WebRequest trwa tak długo?] (Http://stackoverflow.com/questions/2690297/why-does-sending-post-data-w-webrequest-take- tak długo) –

+0

możliwy duplikat: http://stackoverflow.com/questions/2842585/post-a-form-from-a-net-aplikacja –

+0

Czekaj Widzę ciąg POST = "" ale jak ustawić oddzielny post Formularz wartości w tym jednym ciągu? – BigOmega

Odpowiedz

26

Od MSDN

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://contoso.com/PostAccepter.aspx "); 
// Set the Method property of the request to POST. 
request.Method = "POST"; 
// Create POST data and convert it to a byte array. 
string postData = "This is a test that posts this string to a Web server."; 
byte[] byteArray = Encoding.UTF8.GetBytes (postData); 
// Set the ContentType property of the WebRequest. 
request.ContentType = "application/x-www-form-urlencoded"; 
// Set the ContentLength property of the WebRequest. 
request.ContentLength = byteArray.Length; 
// Get the request stream. 
Stream dataStream = request.GetRequestStream(); 
// Write the data to the request stream. 
dataStream.Write (byteArray, 0, byteArray.Length); 
// Close the Stream object. 
dataStream.Close(); 
// Get the response. 
WebResponse response = request.GetResponse(); 
// Display the status. 
Console.WriteLine (((HttpWebResponse)response).StatusDescription); 
// Get the stream containing content returned by the server. 
dataStream = response.GetResponseStream(); 
// Open the stream using a StreamReader for easy access. 
StreamReader reader = new StreamReader (dataStream); 
// Read the content. 
string responseFromServer = reader.ReadToEnd(); 
// Display the content. 
Console.WriteLine (responseFromServer); 
// Clean up the streams. 
reader.Close(); 
dataStream.Close(); 
response.Close(); 

Weź pod uwagę, że informacje muszą być wysyłane w key1 format = wartość1 & klucz2 = value2

+0

dziękuję, więc jest to po prostu ciąg zapytania, właśnie to, czego potrzebowałem, wygrywasz – BigOmega

+2

Tak, w zasadzie, więc uważaj na specjalne znaki. Musisz zakodować klucz i wartość –

2

Oto przykład publikowania w serwisie WWW przy użyciu obiektów HttpWebRequest i HttpWebResponse.

StringBuilder sb = new StringBuilder(); 
    string query = "?q=" + latitude + "%2C" + longitude + "&format=xml&key=xxxxxxxxxxxxxxxxxxxxxxxx"; 
    string weatherservice = "http://api.worldweatheronline.com/free/v1/marine.ashx" + query; 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(weatherservice); 
    request.Referer = "http://www.yourdomain.com"; 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    Stream stream = response.GetResponseStream(); 
    StreamReader reader = new StreamReader(stream); 
    Char[] readBuffer = new Char[256]; 
    int count = reader.Read(readBuffer, 0, 256); 

    while (count > 0) 
    { 
     String output = new String(readBuffer, 0, count); 
     sb.Append(output); 
     count = reader.Read(readBuffer, 0, 256); 
    } 
    string xml = sb.ToString(); 
19

Oto, co działa dla mnie. Jestem pewien, że można go poprawić, więc zachęcamy do sugestii lub edycji, aby było lepiej.

const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod"; 
//This string is untested, but I think it's ok. 
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\" }"; 
try 
{  
    var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL); 
    if (webRequest != null) 
    { 
     webRequest.Method = "POST"; 
     webRequest.Timeout = 20000; 
     webRequest.ContentType = "application/json"; 

    using (System.IO.Stream s = webRequest.GetRequestStream()) 
    { 
     using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s)) 
      sw.Write(jsonData); 
    } 

    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream()) 
    { 
     using (System.IO.StreamReader sr = new System.IO.StreamReader(s)) 
     { 
      var jsonResponse = sr.ReadToEnd(); 
      System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse)); 
     } 
    } 
} 
} 
catch (Exception ex) 
{ 
    System.Diagnostics.Debug.WriteLine(ex.ToString()); 
} 
0

Poniżej znajduje się kod, który odczytuje dane z pliku tekstowego i wysyła je do obsługi do przetwarzania i odbierać dane odpowiedzi z uchwytu i czytać i zapisywać dane w klasie ciąg budowniczy

//Get the data from text file that needs to be sent. 
       FileStream fileStream = new FileStream(@"G:\Papertest.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); 
       byte[] buffer = new byte[fileStream.Length]; 
       int count = fileStream.Read(buffer, 0, buffer.Length); 

       //This is a handler would recieve the data and process it and sends back response. 
       WebRequest myWebRequest = WebRequest.Create(@"http://localhost/Provider/ProcessorHandler.ashx"); 

       myWebRequest.ContentLength = buffer.Length; 
       myWebRequest.ContentType = "application/octet-stream"; 
       myWebRequest.Method = "POST"; 
       // get the stream object that holds request stream. 
       Stream stream = myWebRequest.GetRequestStream(); 
         stream.Write(buffer, 0, buffer.Length); 
         stream.Close(); 

       //Sends a web request and wait for response. 
       try 
       { 
        WebResponse webResponse = myWebRequest.GetResponse(); 
        //get Stream Data from the response 
        Stream respData = webResponse.GetResponseStream(); 
        //read the response from stream. 
        StreamReader streamReader = new StreamReader(respData); 
        string name; 
        StringBuilder str = new StringBuilder(); 
        while ((name = streamReader.ReadLine()) != null) 
        { 
         str.Append(name); // Add to stringbuider when response contains multple lines data 
        } 
       } 
       catch (Exception ex) 
       { 
        throw ex; 
       } 
Powiązane problemy