2010-05-18 10 views
18

Muss der Server einen POST an eine API senden, wie füge ich POST-Werte zu einem WebRequest-Objekt hinzu und wie sende ich es und bekomme die Antwort (es wird eine Zeichenfolge sein)?Wie WebRequest verwenden, um einige Daten POST und Antwort lesen?

Ich muss zwei Werte POST, und manchmal mehr, ich sehe in diesen Beispielen, wo es String postData = "eine Zeichenfolge zum Posten"; aber wie lasse ich die Sache, die ich POST bin, wissen, dass es mehrere Formularwerte gibt?

+0

Beispiel finden Sie in [Warum dauert das Senden von Postdaten mit WebRequest so lange?] (Http://stackoverflow.com/questions/2690297/why-does-sending-post-data-with-webrequest-take- so lang) –

+0

möglich duplizieren: http://stackoverflow.com/questions/2842585/post-a-form-from-a-net-application –

+0

Warte ich sehe den POST = "" string aber wie stelle ich separate Post bilden Werte in dieser einen Zeichenfolge? – BigOmega

Antwort

26

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

berücksichtigen, dass die Informationen müssen & key2 = Wert2

+0

danke, so ist es nur wie eine Abfrage-Zeichenfolge, nur was ich brauchte, gewinnen Sie – BigOmega

+2

Ja, im Grunde, so seien Sie vorsichtig bei Sonderzeichen. Sie müssen Schlüssel und Wert codieren –

2

Hier ist ein Beispiel für die Veröffentlichung in einem Web-Service mit den Objekten HttpWebRequest und 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

Hier ist, was für mich funktioniert. Ich bin mir sicher, dass es verbessert werden kann, also zögern Sie nicht, Vorschläge zu machen oder zu bearbeiten, um es besser zu machen.

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

Unten ist der Code, der die Daten aus der Textdatei lesen und sendet sie zur Verarbeitung an den Handler und die Antwortdaten aus dem Handler empfangen und sie und speichert die Daten im String-Builder-Klasse

lesen
//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; 
       } 
Verwandte Themen