Httpwebrequest - 使用文本文件的POST方法

时间:2012-08-07 18:08:53

标签: c# .net httpwebrequest couchdb

我正在尝试使用.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调用的工作原理。

1 个答案:

答案 0 :(得分: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;
        }

     }
...

在我的情况下,我从一个类中序列化/反序列化我的身体 - 你需要改变它以使用你的文本文件。如果您想轻松删除解决方案,请将SerializetoString方法更改为将文本文件加载到字符串的方法。