WebClient以POST方式发送Web请求

本例使用WebClient以POST方式发送Web请求并下载一个文件,难点是postData的构造,发送Web请求时有的网站要求可能要求Cookies前后一致。其中application/x-www-form-urlencoded会告诉服务器该参数是以param1=value1&param2=value2&param3=value3方式拼接的。

private bool postDataandDownloadFile(string fileName)
{
    string url = "http://www.huiyaosoft.com/test.aspx";
    StringBuilder postData = new StringBuilder();
    postData.AppendFormat("{0}={1}&", "username", "admin");
    postData.AppendFormat("{0}={1}&", "password", "123456");
    postData.AppendFormat("{0}={1}&", "nickname", UrlEncode("辉耀"));
    try
    {
        if (wc == null)
            wc = new System.Net.WebClient();
        wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
        
        // 继承Cookies
        if (!string.IsNullOrEmpty(cookies))
            wc.Headers.Add("Cookie", cookies);

        // Upload the input string using the HTTP 1.0 POST method.
        byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData.ToString());
        // 此处返回的是一个文件
        byte[] byteResult = wc.UploadData(url, "POST", byteArray);
        // 取得Cookies
        cookies = wc.ResponseHeaders["Set-Cookie"];

        if (type == 1 || type == 3)
            writeFile(byteResult, fileName);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    return false;
}

由于设置了"Content-Type"为"application/x-www-form-urlencoded",所以postData必须先进行urlencode。UrlEncode()的作用是将参数进行编码。

public string UrlEncode(string str)
{
    byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str);
    return System.Web.HttpUtility.UrlEncode(byStr);
}

//写byte[]到fileName  
private bool writeFile(byte[] pReadByte, string fileName)
{
    FileStream pFileStream = null;
    try
    {
        pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
        pFileStream.Write(pReadByte, 0, pReadByte.Length);
    }
    catch
    {
        return false;
    }
    finally
    {
        if (pFileStream != null)
            pFileStream.Close();
    }
    return true;
}

(完)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用Spring WebClient进行异步POST请求的代码范例,带有注释解释每个步骤的作用: ```java import org.springframework.http.MediaType; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import java.time.Duration; public class WebClientExample { public static void main(String[] args) { // 创建一个WebClient实例 WebClient webClient = WebClient.builder() // 指定请求超时时间 .clientConnector(new ReactorClientHttpConnector()) .defaultHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE) .defaultHeader("Accept", MediaType.APPLICATION_JSON_VALUE) .baseUrl("http://localhost:8080") .build(); // 构造请求参数 MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("param1", "value1"); formData.add("param2", "value2"); // 发送POST请求 Mono<ClientResponse> responseMono = webClient.post() // 指定请求路径 .uri("/api/path") // 设置请求体 .body(BodyInserters.fromFormData(formData)) // 发送请求并返回响应结果 .exchange(); // 处理响应结果 responseMono.subscribe(response -> { // 打印响应状态码 System.out.println(response.statusCode()); // 打印响应头 response.headers().asHttpHeaders().forEach((name, values) -> { System.out.println(name + ": " + values); }); // 打印响应体 response.bodyToMono(String.class).subscribe(System.out::println); }); } } ``` 在这个例子中,我们创建了一个WebClient实例,并指定了请求超时时间、默认请求头、请求的基础URL等信息。然后,我们构造了一个包含请求参数的MultiValueMap对象,并将其作为请求发送POST请求WebClientpost()方法返回一个RequestHeadersSpec对象,该对象可以用于设置请求头、请求体等信息。在这个例子中,我们使用uri()方法指定了请求路径,并使用body()方法设置了请求体。 最后,我们调用exchange()方法发送请求并返回响应结果。exchange()方法返回一个Mono<ClientResponse>对象,我们可以使用subscribe()方法对其进行订阅,然后在回调函数中处理响应结果。在这个例子中,我们打印了响应状态码、响应头和响应体。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值