我需要使用“HTTP Post”与WebClient Post一些数据到特定的URL我有。
现在,我知道这可以用WebRequest完成,但由于某些原因,我想使用WebClient代替。这可能吗?如果是这样,谁能给我举个例子或者给我指出正确的方向?
我需要使用“HTTP Post”与WebClient Post一些数据到特定的URL我有。
现在,我知道这可以用WebRequest完成,但由于某些原因,我想使用WebClient代替。这可能吗?如果是这样,谁能给我举个例子或者给我指出正确的方向?
当前回答
使用WebClient。UploadString或WebClient。UploadData可以轻松地将数据POST到服务器。我将展示一个使用UploadData的示例,因为UploadString的使用方式与DownloadString相同。
byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
System.Text.Encoding.ASCII.GetBytes("field1=value1&field2=value2") );
string sret = System.Text.Encoding.ASCII.GetString(bret);
更多:http://www.daveamenta.com/2008-05/c-webclient-usage/
其他回答
大多数答案都是旧的。只是想分享一下对我有用的方法。为了实现异步操作,例如在。net 6.0 Preview 7中使用WebClient异步发布数据到特定的URL, . net Core和其他版本都可以使用WebClient。UploadStringTaskAsync方法。
使用命名空间System.Net;对于ResponseType类来捕获来自服务器的响应,我们可以使用这个方法将数据POST到特定的URL。请确保在调用此方法时使用await关键字
public async Task<ResponseType> MyAsyncServiceCall()
{
try
{
var uri = new Uri("http://your_uri");
var body= "param1=value1¶m2=value2¶m3=value3";
using (var wc = new WebClient())
{
wc.Headers[HttpRequestHeader.Authorization] = "yourKey"; // Can be Bearer token, API Key etc.....
wc.Headers[HttpRequestHeader.ContentType] = "application/json"; // Is about the payload/content of the current request or response. Do not use it if the request doesn't have a payload/ body.
wc.Headers[HttpRequestHeader.Accept] = "application/json"; // Tells the server the kind of response the client will accept.
wc.Headers[HttpRequestHeader.UserAgent] = "PostmanRuntime/7.28.3";
string result = await wc.UploadStringTaskAsync(uri, body);
return JsonConvert.DeserializeObject<ResponseType>(result);
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
有一个内置的方法叫做UploadValues,它可以发送HTTP POST(或任何类型的HTTP方法),并以适当的数据格式处理请求体的构造(用“&”连接参数并通过url编码转义字符):
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);
}
使用简单客户端。UploadString(地址、内容);正常工作很好,但我认为应该记住,如果没有返回HTTP成功状态码,将抛出webeexception。我通常这样处理,打印远程服务器返回的任何异常消息:
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;
}
下面是简单明了的答案:
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;
}
//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());
}
}