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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM