C #에서 WebClient를 사용하여 특정 URL에 데이터를 게시하는 방법


319

WebClient에서 "HTTP Post"를 사용하여 일부 데이터를 특정 URL에 게시해야합니다.

이제 WebRequest 로이 작업을 수행 할 수 있다는 것을 알고 있지만 어떤 이유로 WebClient를 대신 사용하고 싶습니다. 가능합니까? 그렇다면 누군가가 나에게 몇 가지 예를 보여 주거나 올바른 방향으로 나를 가리킬 수 있습니까?

답변:


374

방금 해결책을 찾았고 생각보다 쉽습니다. :)

솔루션은 다음과 같습니다.

string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";

using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(URI, myParameters);
}

그것은 매력처럼 작동합니다 :)


28
nitpick : HttpRequestHeader.ContentType여기에 열거 형 멤버 를 사용하는 것이 좋습니다 web.Headers[HttpRequestHeader.ContentType]: p
— Alex

12
또 다른 nitpick, .dispose 또는 "using"관용구를 사용하여 웹 클라이언트를 올바르게 처리해야합니다. using (WebClient wc = new WebClient ()) {// 코드는 여기}
— Mikey Hogarth

1
@RobinVanPersi ShikataGanai (Rafik bari)는 다른 답변 ( stackoverflow.com/a/13061805/1160796 )이 인코딩을 처리하기 때문에 더 나은 것이라고 생각 합니다.
— basher

3
@ alpsystems.com IDisposable 객체는 프로그래머가 감싸거나 .Dispose ()를 명시 적으로 호출하여 올바르게 폐기해야합니다. 가비지 콜렉터는 파일 핸들러, 데이터베이스 연결 등과 같은 관리되지 않는 자원을 추적 할 수 없습니다.
— ccalboni

1
@ccalboni의 설명을 확장합니다. 경우에 따라 가비지 수집기는 소멸자를 호출하여 관리되지 않는 리소스 등을 정리합니다 (예 :을 ( 를) 포함하는 WebClient에서 상속 함 ). 문제는 가비지 수집기가 수집 결정을 할 때 관리되지 않는 리소스를 고려하지 않기 때문에 임의로 시간이 오래 걸릴 수 있다는 것입니다. 고가의 자원은 가능한 빨리 정리해야합니다. 예를 들어, 불필요한 파일 핸들을 열어두면 파일이 다른 코드에 의해 삭제되거나 기록되지 않을 수 있습니다. Component~Component() {Dispose(false);}
— Brian

361

HTTP POST (또는 모든 종류의 HTTP 메소드)를 보낼 수 있고 올바른 형식의 데이터 형식으로 요청 본문 ( "&"으로 매개 변수 연결 및 URL 인코딩으로 이스케이프 처리)을 처리 할 수있는 UploadValues 라는 내장 메소드 가 있습니다.

using(WebClient client = new WebClient())
{
    var reqparm = new System.Collections.Specialized.NameValueCollection();
    reqparm.Add("param1", "<any> kinds & of = ? strings");
    reqparm.Add("param2", "escaping is already handled");
    byte[] responsebytes = client.UploadValues("http://localhost", "POST", reqparm);
    string responsebody = Encoding.UTF8.GetString(responsebytes);
}

1
모델을 컨트롤러에 게시하려면 어떻게합니까? 여전히 reqparm.Add (string, string)를 사용할 수 있습니까?
— Burak Karakuş

6
@ BurakKarakuş 당신은 당신이 본문에 JSON을 보내시겠습니까? 그런 다음 WebClient.UploadString 을 사용할 수 있습니다 . 헤더에 Content-Type : application / json을 추가하는 것을 잊지 마십시오.
— Endy Tjahjono

@EndyTjahjono : 라디오 버튼 값을 게시하는 방법 3 개의 라디오 버튼이 동일한 그룹에 속한다고 가정합니다.
— Asad Refai

응답 코드는 어떻게 받습니까? 응답 헤더? 응답을 구문 분석해야합니까? 그렇게하는 쉬운 방법이 있습니까?
— Jay Sullivan

경고. namevalueCollection donest는 같은 키를 허용하지 않으므로 이상한 행동을 유발할 수 있습니다
— bh_earth0

40

사용 WebClient.UploadString하거나 WebClient.UploadData서버에 데이터를 쉽게 게시 할 수 있습니다. UploadString은 DownloadString과 같은 방식으로 사용되므로 UploadData를 사용하는 예제를 보여 드리겠습니다.

byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
                System.Text.Encoding.ASCII.GetBytes("field1=value1&amp;field2=value2") );

            string sret = System.Text.Encoding.ASCII.GetString(bret);

더 : http://www.daveamenta.com/2008-05/c-webclient-usage/


5
사용하는 것이 좋습니다 : client.Encoding = System.Text.UTF8Encoding.UTF8; 문자열 varValue = Uri.EscapeDataString (value);
— Yuriy Vikulov

23
string URI = "site.com/mail.php";
using (WebClient client = new WebClient())
{
    System.Collections.Specialized.NameValueCollection postData = 
        new System.Collections.Specialized.NameValueCollection()
       {
              { "to", emailTo },  
              { "subject", currentSubject },
              { "body", currentBody }
       };
    string pagesource = Encoding.UTF8.GetString(client.UploadValues(URI, postData));
}

21
//Making a POST request using WebClient.
Function()
{    
  WebClient wc = new WebClient();

  var URI = new Uri("http://your_uri_goes_here");

  //If any encoding is needed.
  wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
  //Or any other encoding type.

  //If any key needed

  wc.Headers["KEY"] = "Your_Key_Goes_Here";

  wc.UploadStringCompleted += 
      new UploadStringCompletedEventHandler(wc_UploadStringCompleted);

  wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");    
}

void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)    
{  
  try            
  {          
     MessageBox.Show(e.Result); 
     //e.result fetches you the response against your POST request.         
  }
  catch(Exception exc)         
  {             
     MessageBox.Show(exc.ToString());            
  }
}

비동기 버전을 사용하는 것이 위의 모든 것이 실행을 게시하고 차단하는 것이 좋습니다.
— Juan

wc__UploadStringCompleted를 수정하려면 double __을 제거하십시오
— Joel Davis

1
위의 모든 답변은 테스트에서 잘 작동하지만 인터넷이 좋지 않은 실제 상황에서는 이것이 더 나은 답변입니다.
— Joel Davis

2

간단한 사용은 client.UploadString(adress, content);정상적으로 작동하지만 WebExceptionHTTP 성공 상태 코드가 반환되지 않으면 a가 발생 한다는 것을 기억해야한다고 생각합니다 . 나는 보통 원격 서버가 반환하는 예외 메시지를 인쇄하기 위해 다음과 같이 처리합니다.

try
{
    postResult = client.UploadString(address, content);
}
catch (WebException ex)
{
    String responseFromServer = ex.Message.ToString() + " ";
    if (ex.Response != null)
    {
        using (WebResponse response = ex.Response)
        {
            Stream dataRs = response.GetResponseStream();
            using (StreamReader reader = new StreamReader(dataRs))
            {
                responseFromServer += reader.ReadToEnd();
                _log.Error("Server Response: " + responseFromServer);
            }
        }
    }
    throw;
}

감사합니다, 오 글라스 오류를 찾기 위해 많은 시간을 보냈으며 코드에서 더 많은 정보를 수정할 수 있습니다.
— Kate

1

모델 보내기 webapiclient를 사용하여 json 매개 변수 요청을 직렬화하십시오.

PostModel.cs

    public string Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }

WebApiClient.cs

internal class WebApiClient  : IDisposable
  {

    private bool _isDispose;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public void Dispose(bool disposing)
    {
        if (!_isDispose)
        {

            if (disposing)
            {

            }
        }

        _isDispose = true;
    }

    private void SetHeaderParameters(WebClient client)
    {
        client.Headers.Clear();
        client.Headers.Add("Content-Type", "application/json");
        client.Encoding = Encoding.UTF8;
    }

    public async Task<T> PostJsonWithModelAsync<T>(string address, string data,)
    {
        using (var client = new WebClient())
        {
            SetHeaderParameters(client);
            string result = await client.UploadStringTaskAsync(address, data); //  method:
    //The HTTP method used to send the file to the resource. If null, the default is  POST 
            return JsonConvert.DeserializeObject<T>(result);
        }
    }
}

비즈니스 발신자 방법

    public async Task<ResultDTO> GetResultAsync(PostModel model)
    {
        try
        {
            using (var client = new WebApiClient())
            {
                var serializeModel= JsonConvert.SerializeObject(model);// using Newtonsoft.Json;
                var response = await client.PostJsonWithModelAsync<ResultDTO>("http://www.website.com/api/create", serializeModel);
                return response;
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

    }

0

선명한 답변은 다음과 같습니다.

public String sendSMS(String phone, String token) {
    WebClient webClient = WebClient.create(smsServiceUrl);

    SMSRequest smsRequest = new SMSRequest();
    smsRequest.setMessage(token);
    smsRequest.setPhoneNo(phone);
    smsRequest.setTokenId(smsServiceTokenId);

    Mono<String> response = webClient.post()
          .uri(smsServiceEndpoint)
          .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
          .body(Mono.just(smsRequest), SMSRequest.class)
          .retrieve().bodyToMono(String.class);

    String deliveryResponse = response.block();
    if (deliveryResponse.equalsIgnoreCase("success")) {
      return deliveryResponse;
    }
    return null;
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.