[C#] WebRequest의 본문 데이터 설정

ASP.NET에서 웹 요청을 만들고 있는데 본문에 많은 데이터를 추가해야합니다. 어떻게하나요?

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



답변

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

내 코드 중 하나에서 :

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


답변

최신 정보

내 다른 SO 대답을 참조하십시오.


실물

var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");

string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding

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

var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();


답변

이 주제의 답변은 모두 훌륭합니다. 그러나 나는 다른 것을 제안하고 싶습니다. 대부분의 경우 API를 받았으며이를 C # 프로젝트에 포함하려고합니다. Postman을 사용하면 거기에서 api 호출을 설정하고 테스트 할 수 있으며 제대로 실행되면 ‘코드’를 클릭하기 만하면 작업중인 요청이 ac # 스 니펫에 작성됩니다. 이렇게 :

var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "development+XXXXXXXX-admin@XXXXXXX.XXXX");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

위의 코드는 쉽게 설치할 수있는 Nuget 패키지 RestSharp에 따라 다릅니다.


답변