HttpClient设置与内容类型的边界

时间:2013-08-28 23:39:14

标签: c# javascript httpclient content-type boundary

我有点混乱的情况,我希望有人可以提供解决方案。所以,在我提供一些背景知识的时候请和我一起露面。基本上我使用javascript与第三方服务进行通信。作为其身份验证过程的一部分,他们需要发布消息的“multipart / form”主体,包括要在md5中加密的图像,这将添加到包含日期和其他一些内容的字符串中,然后再运行HMAc / SHA1在上面。所以最后他们有多部分主体,日期和身份验证哈希,以便进行身份验证,然后读取图像。

这适用于所有移动设备,除了windowsPhone ..(我知道,IE的问题......谁会想到?)。他们的httpwebrequest不包含'Date'标题..所以没有身份验证。这意味着我必须使用Windows手机本机并在C#中使用新发布的httpclient代码。现在我是一个C#noob,所以这可能是简单的解决方案。我已经通过将所有内容传递给c#以及使用c#进行帖子来获得身份验证,但是他们无法读取正文,因为我发现发送边界的唯一方法是将内容定义为multipartformDatacontent并发送内容方式改变了身体,因此身份验证失败。

我的javascript类似于:

var boundary = "------------ThIs_Is_tHe_bouNdaRY_";
var part1Array = [];
var part1 = "--"+boundary + "\r\n"+
    "Content-Disposition: form-data; name=\"image\"\r\n"+
    "Content-Type: image/jpg\r\n"+
    "\r\n";
var part3Array = [];
var part3 = "\r\n" + boundary +"--";
for(var p1=0; p1<part1.length; p1++){
    part1Array.push(part1.charCodeAt(p1));
}
for(var p3=0; p3<part3.length; p3++){
    part3Array.push(part3.charCodeAt(p3));
}
var bodyContent = part1Array.concat(imageArray,part3Array);

//hash this

var authMessage = bodyContentHash +"\n"+ contentType +"\n"+ todayString +"\n"+ pathandstuff;
// -hmac -sha1 -base64

和c#是:

HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, path);

request.Headers.Date = DateTime.ParseExact(todaydate, "ddd',' dd MMM yyyy HH:mm:ss 'GMT'", new CultureInfo("en-US"), DateTimeStyles.AssumeUniversal);
request.Headers.Add("Accept", "application/json; charset=utf-8");
request.Headers.Add("Authorization", auth);

byte[] body = Convert.FromBase64String(bodyData);
request.Content = new ByteArrayContent(body);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
request.Content.Headers.Add("boundary", "------------ThIs_Is_tHe_bouNdaRY_");

HttpResponseMessage response = client.SendAsync(request).Result;
string resultCode = response.StatusCode.ToString();
string responseBodyAsText = await response.Content.ReadAsStringAsync();

这非常有用..正文内容和标题一样正确..除内容类型标题外应该是:

request.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data, boundary=------------ThIs_Is_tHe_bouNdaRY_");

除此之外引发System.FormatException错误。 任何帮助表示感谢。

3 个答案:

答案 0 :(得分:7)

我们通过手动清除和重新添加内容类型而无需验证来解决此问题 似乎MediaTypeHeaderValue()类不喜欢边界标记。

而不是使用:

content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data; boundary=----FLICKR_MIME_20140415120129--");

我们做了以下事情:

content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=----FLICKR_MIME_20140415120129--");

一旦我们做了这个改变,一切都正常。

(请注意,如果这有任何不同,这是在WinRT上)

答案 1 :(得分:4)

使用HttpClient

 request.Content.Headers.Add("ContentType", "multipart/form-data, boundary=------------ThIs_Is_tHe_bouNdaRY_");

你可以使用HttpWebRequest

 myHttpWebRequest.Date = DateTime.Now;
 myHttpWebRequest.ContentType = "multipart/form-data, boundary=------------ThIs_Is_tHe_bouNdaRY_";

答案 2 :(得分:1)

我在这里发布我的代码,也许这会帮助其他人像我一样苦苦挣扎,在我的情况下,这可行并将文件上传到我的帐户(不是银行业务,而是安全的云文件产品)

 public  string UploadFile(string endpointUrl, string filePath, string accessToken)
    {

        FileStream fs = null;
        Stream rs = null;
        string result = "";
        try
        {

            string uploadFileName = System.IO.Path.GetFileName(filePath);

            fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

            var request = (HttpWebRequest)WebRequest.Create(endpointUrl);
            request.Method = WebRequestMethods.Http.Post;
            request.AllowWriteStreamBuffering = false;
            request.SendChunked = true;
            String CRLF = "\r\n"; // Line separator required by multipart/form-data.        
            long timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();

            string boundary = timestamp.ToString("x");
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            request.Headers.Add("Authorization", "Bearer " + accessToken);                             

            long bytesAvailable = fs.Length;
            long maxBufferSize = 1 * 1024 * 1024;


            rs = request.GetRequestStream();
            byte[] buffer = new byte[50];
            int read = 0;

            byte[] buf = Encoding.UTF8.GetBytes("--" + boundary + CRLF);
            rs.Write(buf, 0, buf.Length);

            buf = Encoding.UTF8.GetBytes("Content-Disposition: form-data; name=\"body\"; filename=\"" + uploadFileName + "\"" + CRLF);                
            rs.Write(buf, 0,buf.Length);

            buf = Encoding.UTF8.GetBytes("Content-Type: application/octet-stream;" + CRLF);
            rs.Write(buf, 0, buf.Length);

            buf = Encoding.UTF8.GetBytes(CRLF);
            //writer.append("Content-Type: application/octet-stream;").append(CRLF);
            rs.Write(buf, 0, buf.Length);
            rs.Flush();


            long bufferSize = Math.Min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, read);
            }
            buf = Encoding.UTF8.GetBytes(CRLF);                
            rs.Write(buf, 0, buf.Length);
            rs.Flush();


            // End of multipart/form-data.
            buffer = Encoding.UTF8.GetBytes("--" + boundary + "--" + CRLF);
            rs.Write(buffer, 0, buffer.Length);

            using (var response = request.GetResponse())
            using (var responseStream = response.GetResponseStream())
            using (var reader = new StreamReader(responseStream))
            {

                result = reader.ReadToEnd();
            }
        }
        catch (Exception e)
        {
            result = e.InnerException != null ? e.InnerException.Message : e.Message;  
        }

        return result;
    }