2012-08-07 14 views
0

我想用.NET類而不是curl命令行復制一個Couch數據庫。我從來沒有使用過WebRequest或Httpwebrequest,但我正試圖用下面的腳本來發出請求。Httpwebrequest - 使用文本文件的POST方法

下面是CouchDB的複製JSON腳本(我知道這工作):

{ ""_id"":"database_replicate8/7/12", "source":sourcedb, ""target"":"targetDB", ""create_target"":true, ""user_ctx"": { ""roles"": ["myrole"] } } 

以上腳本被放入一個文本文件,sourcefile.txt。我想採用這一行,並使用.NET功能將其放入POST Web請求中。

查看後,我選擇使用httpwebrequest類。下面是我迄今爲止 - 我得到這個從http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

HttpWebRequest bob = (HttpWebRequest)WebRequest.Create("sourceDBURL"); 
bob.Method = "POST"; 
bob.ContentType = "application/json"; 
byte[] bytearray = File.ReadAllBytes(@"sourcefile.txt"); 
Stream datastream = bob.GetRequestStream(); 
datastream.Write(bytearray, 0, bytearray.Length); 
datastream.Close(); 

我要對這個正確?我對網絡技術比較陌生,並且仍然在學習http調用的工作方式。

回答

0

這裏有一個方法,我用來創建POST請求:

private static HttpWebRequest createNewPostRequest(string apikey, string secretkey, string endpoint) 
{ 
    HttpWebRequest request = WebRequest.Create(endpoint) as HttpWebRequest; 
    request.Proxy = null; 
    request.Method = "POST"; 
    //Specify the xml/Json content types that are acceptable. 
    request.ContentType = "application/xml"; 
    request.Accept = "application/xml"; 

    //Attach authorization information 
    request.Headers.Add("Authorization", apikey); 
    request.Headers.Add("Secretkey", secretkey); 
    return request; 
} 

在我的主要方法我這樣稱呼它:

HttpWebRequest request = createNewPostRequest(apikey, secretkey, endpoint); 

,然後將我的數據傳遞給這樣的方法:

string requestBody = SerializeToString(requestObj); 

byte[] byteStr = Encoding.UTF8.GetBytes(requestBody); 
request.ContentLength = byteStr.Length; 

using (Stream stream = request.GetRequestStream()) 
{ 
    stream.Write(byteStr, 0, byteStr.Length); 
} 

//Parse the response 
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
{ 
    //Business error 
    if (response.StatusCode != HttpStatusCode.OK) 
    { 
     Console.WriteLine(string.Format("Error: response status code is{0}, at time:{1}", response.StatusCode, DateTime.Now.ToString())); 

     return "error"; 
    } 
    else if (response.StatusCode == HttpStatusCode.OK)//Success 
    { 
     using (Stream respStream = response.GetResponseStream()) 
     { 
      XmlSerializer serializer = new XmlSerializer(typeof(SubmitReportResponse)); 
      reportReq = serializer.Deserialize(respStream) as SubmitReportResponse; 
     } 

    } 
... 

在我來說,我從序列化類/反序列化我的身體 - 你需要改變這個給我們e您的文本文件。如果您想簡單地解決方案,則將SerializetoString方法更改爲將文本文件加載到字符串的方法。