发送名为Mulitpart Data的HttpClient

时间:2017-07-06 12:32:11

标签: c# httpclient multipartentity

我尝试使用c#HttpClient

将多部分内容作为帖子发送到WebService

我的代码是以下

public string UploadDocument(Stream stream)
{

  MultipartContent multipart = new MultipartContent();
  //multipart.Add(new StreamContent(stream), "importFile");
  StreamContent content = new StreamContent(stream);
  multipart.Add(content);

  Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

  HttpResponseMessage response = Client.PostAsync("URL to webservice", multipart).Result;
  string result = response.Content.ReadAsStringAsync().Result;

  //Wirft eine Exception wenn der StatusCode nicht 200 (OK) ist.
  response.EnsureSuccessStatusCode();

  return result;


}

我需要命名流内容,我该怎么做。

我发现了Java方法,但是在C#中我找不到参数“Name”

这里是Java示例(参见“importFile”)

httpRequest = new HttpPostwebviewer/?action=import");
    // set headers
    httpRequest.setHeader(HEADER_NAME_ACCEPT, "application/json");
    // prepare upload entity
    MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
    meBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    meBuilder.setCharset(Consts.UTF_8);
    meBuilder.addPart("importFile", contentBody);
    // build upload entity
    HttpEntity uploadEntity = meBuilder.build();
    // set properties to http request
    ((HttpPost) httpRequest).setEntity(uploadEntity);

1 个答案:

答案 0 :(得分:0)

你可以使用System.Net.HttpWebRequest来做同样的事情,下面是我正在使用的代码:

 public static void UploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
    {
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
        url = handlerLocation + url;
        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
        wr.ContentType = "multipart/form-data; boundary=" + boundary;
        wr.Method = "POST";
        wr.KeepAlive = true;
        wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

        Stream rs = wr.GetRequestStream();

        string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
        foreach (string key in nvc.Keys)
        {
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, key, nvc[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            rs.Write(formitembytes, 0, formitembytes.Length);
        }
        rs.Write(boundarybytes, 0, boundarybytes.Length);

        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
        string header = string.Format(headerTemplate, paramName, file, contentType);
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        rs.Write(headerbytes, 0, headerbytes.Length);

        FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            rs.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();

        byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
        rs.Write(trailer, 0, trailer.Length);
        rs.Close();

        WebResponse wresp = null;
        try
        {
            wresp = wr.GetResponse();
            Stream stream2 = wresp.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);
        }
        catch (Exception ex)
        {
            //WriteTrace(ex.Message);
            if (wresp != null)
            {
                wresp.Close();
                wresp = null;
            }
        }
        finally
        {
            wr = null;
        }
    }