2010-05-18 10 views
18

सर्वर को एक एपीआई में पोस्ट करने की आवश्यकता है, मैं WebRequest ऑब्जेक्ट में POST मान कैसे जोड़ूं और मैं इसे कैसे भेजूं और प्रतिक्रिया प्राप्त करूं (यह एक स्ट्रिंग होगी)?कुछ डेटा पोस्ट करने और प्रतिक्रिया पढ़ने के लिए WebRequest का उपयोग कैसे करें?

मुझे दो मूल्यों को पोस्ट करने की आवश्यकता है, और कभी-कभी, मैं इन उदाहरणों में देखता हूं जहां यह स्ट्रिंग postData = "पोस्ट करने के लिए एक स्ट्रिंग" कहता है; लेकिन मैं यह जानने के लिए पोस्ट कर रहा हूं कि कई रूपों के मूल्य क्या हैं?

+0

उदाहरण में पाया जा सकता है [WebRequest के साथ पोस्ट डेटा क्यों भेजना इतना लंबा लगता है?] (Http://stackoverflow.com/questions/2690297/why-does-sending-post-data-with-webrequest-take- इतने लंबे) –

+0

संभावित डुप्लिकेट: http://stackoverflow.com/questions/2842585/post-a-form-from-a-net- appplication –

+0

रुको मैं POST = "" स्ट्रिंग देखता हूं लेकिन मैं अलग पोस्ट कैसे सेट करूं प्रपत्र उस स्ट्रिंग में मूल्य? – BigOmega

उत्तर

26

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

को ध्यान में रखें कि जानकारी प्रारूप कुंजी 1 में भेजा जाना चाहिए = मान 1 & कुंजी 2 = मान 2

+0

धन्यवाद, तो यह सिर्फ एक क्वेरी स्ट्रिंग की तरह है, बस मुझे जो चाहिए, आप – BigOmega

+2

जीतें हां, मूल रूप से, इसलिए विशेष वर्णों के बारे में सावधान रहें। आपको कुंजी और मूल्य एन्कोड करने की आवश्यकता है –

2

यहां HttpWebRequest और 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

यहां मेरे लिए क्या काम करता है। मुझे यकीन है कि इसे बेहतर किया जा सकता है, इसलिए इसे बेहतर बनाने के लिए सुझाव देने या संपादित करने में संकोच न करें।

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

नीचे कोड है कि पाठ फ़ाइल से डेटा पढ़ सकते हैं और प्रसंस्करण के लिए हैंडलर को भेज देता है और स्ट्रिंग बिल्डर कक्षा में डेटा हैंडलर से प्रतिक्रिया डेटा प्राप्त करते हैं और इसे पढ़ा और स्टोर है

//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; 
       }