web-dev-qa-db-ja.com

WebRequestの本文データを設定する

ASP.NETでWeb要求を作成していますが、大量のデータを本文に追加する必要があります。それ、どうやったら出来るの?

var request = HttpWebRequest.Create(targetURL);
request.Method = "PUT";
response = (HttpWebResponse)request.GetResponse();
113
William Calleja

HttpWebRequest.GetRequestStreamを使用

http://msdn.Microsoft.com/en-us/library/d4cek6cc.aspx のコード例

string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);

私自身のコードの1つから:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
    cmisAtomEntry.WriteXml(xmlWriter);
}

try 
{    
    return (HttpWebResponse)request.GetResponse();  
}
catch (WebException wex)
{
    var httpResponse = wex.Response as HttpWebResponse;
    if (httpResponse != null)
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in a http error {2} {3}.",
            method,
            uri,
            httpResponse.StatusCode,
            httpResponse.StatusDescription), wex);
    }
    else
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in an error.",
            method,
            uri), wex);
    }
}
catch (Exception)
{
    throw;
}
96

これは役立つはずです:

var request = (HttpWebRequest)WebRequest.Create("http://example.com/page.asp");

string stringData = ""; //place body here
var data = Encoding.ASCII.GetBytes(stringData); // or UTF8

request.Method = "PUT";
request.ContentType = ""; //place MIME type here
request.ContentLength = data.Length;

var newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
43
Evan Mulawski