HttpClient使用方法(包括POST文件)

最近在做跨系统的数据交互业务,从.Net的系统提交数据到Java的系统。

简单的表单Get、POST都没问题,但是有个功能是要提交普通文本和文件,试了好多都有问题,最后用HttpClient小折腾了一下就OK了。

①先说带有文件的POST方法

public async void SendRequest()
{
    HttpClient client = new HttpClient();
    client.MaxResponseContentBufferSize = 256000;
    client.DefaultRequestHeaders.Add("user-agent", "User-Agent    Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; MALNJS; rv:11.0) like Gecko");//设置请求头
    string url = ConfigurationManager.AppSettings["apiUrl"];
    HttpResponseMessage response;
    MultipartFormDataContent mulContent = new MultipartFormDataContent("----WebKitFormBoundaryrXRBKlhEeCbfHIY");//创建用于可传递文件的容器

    string path = "D:\white.png";

    // 读文件流
    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
    HttpContent fileContent = new StreamContent(fs);//为文件流提供的HTTP容器
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");//设置媒体类型
    mulContent.Add(fileContent, "myFile", "white.png");//这里第二个参数是表单名,第三个是文件名。如果接收的时候用表单名来获取文件,那第二个参数就是必要的了 
    mulContent.Add(new StringContent("253"), "id"); //普通的表单内容用StringContent
    mulContent.Add(new StringContent("english Song"), "desc"); 
    response = await client.PostAsync(new Uri(url), mulContent); 
    response.EnsureSuccessStatusCode(); 
    string result = await response.Content.ReadAsStringAsync(); 
}

  

看一下是如何接收的

public void ProcessRequest(HttpContext context)
{
    var file = Request.Files["myFile"];
    var id = Request.Form["id"];//253
    var text = Request.Form["desc"];//english Song
    if (file != null && !String.IsNullOrEmpty(text))
    {
        file.SaveAs("/newFile/" + Guid.NewGuid().ToString() + "/" + file.FileName);//FileName是white.png
    }
    Response.Flush();
    Response.End();
}

实在是相当简单

②POST普通表单请求

只需将设置Http正文和标头的操作替换即可

List<KeyValuePair<string, string>> pList = new List<KeyValuePair<string, string>>();
pList.Add(new KeyValuePair<string, string>("id", "253"));
pList.Add(new KeyValuePair<string, string>("desc", "english Song"));
HttpContent content = new FormUrlEncodedContent(pList);
HttpResponseMessage response = await client.PostAsync(new Uri(url), content);

③GET

string url = ConfigurationManager.AppSettings["apiUrl"];
string result = await client.GetStringAsync(new Uri(url+"?id=123"));
原文地址:https://www.cnblogs.com/TiestoRay/p/4877978.html