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

最近在作跨系統的數據交互業務,從.Net的系統提交數據到Java的系統。api

簡單的表單Get、POST都沒問題,可是有個功能是要提交普通文本和文件,試了好多都有問題,最後用HttpClient小折騰了一下就OK了。async

 

①先說帶有文件的POST方法ide

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

  

看一下是如何接收的ui

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

實在是至關簡單url

 

②POST普通表單請求spa

只需將設置Http正文和標頭的操做替換便可code

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

 

③GETorm

string url = ConfigurationManager.AppSettings["apiUrl"];
string result = await client.GetStringAsync(new Uri(url+"?id=123"));
相關文章
相關標籤/搜索