0

我正在尝试使用 .NET 类而不是 curl 命令行来复制 Couch 数据库。我以前从未使用过 WebRequest 或 Httpwebrequest,但我正在尝试使用它们通过下面的脚本发出发布请求。

这是用于 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 调用的工作原理。

4

1 回答 1

0

Here is a method I use for creating POST requests:

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

Within my main method I call it like this:

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

and I then pass my data to the method like this:

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

     }
...

In my case I serialize/deserialize my body from a class - you will need to alter this to use your text file. If you want an easy drop in solution, then change the SerializetoString method to a method that loads your text file to a string.

于 2012-08-07T18:21:08.850 回答