HttpClient使用JToken和字符串发布MultipartFormDataContent返回404错误

时间:2015-05-25 07:40:27

标签: c# json httpclient

我需要发布一个请求包含:xml定义为字符串和json。我在正确设置内容和处理JToken方面遇到了问题 原始请求在Fiddler中如下所示:

内容类型:multipart / form-data;边界= ------------------------- acebdf13572468 用户代理:Fiddler 授权:基本QURNSU46QURNSU4 = 内容长度:888 主持人:localhost

--------------------------- acebdf13572468 内容处理:表格数据; NAME = “fieldNameHere”;文件名= “testfile2.txt” 内容类型:text / plain

这是用于eB EC插件测试环境中的文件管理测试的第二个测试文件。 --------------------------- acebdf13572468 内容处理:表格数据; NAME = “fieldNameHere” Content-Type:application / json

{   “实例”:{     “className”:“文件”,     “schemaName”:“EB”,     “relationshipInstances”:[        {           “方向”:“落后”,           “className”:“DocumentFiles”,           “schemaName”:“EB”,           “relatedInstance”:{              “className”:“文档”,              “schemaName”:“EB”,              “instanceId”:“4”           }        }     ]     “properties”:{         “名称”:“testfile2.txt”     }   } }

--------------------------- acebdf13572468 -

我有这个方法并得到404错误:

     public static string PostXMLStringAndJasonInOneRequest(int instanceId)
    {
        // Creating json that describes document with property 'name' 
        JObject documentToPost = CreateClassInstance("File", "eB", null, new KeyValuePair<string, object>("Name", "MyTestDocument.txt"));

        JObject relationship = CreateRelationshipClassInstance("DocumentFiles", "eB", null, "backward");

        // specifying document parent that is existing project with its id 
        JObject documentParent = CreateClassInstance("Document", "eB", instanceId.ToString());

        JToken json = CreateJson(documentToPost, relationship, documentParent);
        Uri uri = new Uri("http://localhost/wsg/v2.0/xxxx");

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", "Basic QURNSU46QURNSU4=");
            MultipartFormDataContent form = new MultipartFormDataContent();
            // TO-DO: save the xml string contents here
            HttpContent content = new ByteArrayContent(GetBytes("<node>this is a text</node>"));

            // HttpContent content = new StringContent("<node>this is a text</node>");
            content.Headers.Add("Content-Type", "application/xml");

            form.Add(content);

            // TO-DO Save json  - not hard coded the value of json
            string jsonText = @"{
                  ""instance"": {
                    ""className"": ""File"",
                    ""schemaName"": ""EB"",
                    ""relationshipInstances"": [
                       {
                          ""direction"": ""backward"",
                          ""className"": ""DocumentFiles"",
                          ""schemaName"": ""EB"",
                          ""relatedInstance"": {
                             ""className"": ""Document"",
                             ""schemaName"": ""EB"",
                             ""instanceId"": ""120""
                          }
                       }
                    ],
                    ""properties"": {
                        ""Name"": ""testfile2.xml""
                    }
                  }
                }";

            HttpContent jsonContent = new ByteArrayContent(GetBytes(jsonText));
            jsonContent.Headers.Add("Content-Type", "application/json");
            // TO-DO put json not jsonText
            form.Add(jsonContent);
            HttpResponseMessage response = client.PostAsync(uri, form).Result;
            if (response.StatusCode != HttpStatusCode.Created)
            {
                return "error"; // handle error 
            }
            return response.Content.ReadAsStringAsync().Result;
        }
    }

1 个答案:

答案 0 :(得分:0)

// To create multipartcontent 

    // 404 is an error in my url address

        private static HttpContent CreateMultipartContent(JToken json, Stream file, string fileName)
                {
                    MultipartContent content = new MultipartContent("form-data", Guid.NewGuid().ToString());

                    StringContent jsonPart = new StringContent(json.ToString());
                    jsonPart.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
                    jsonPart.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    StreamContent filePart = new StreamContent(file);
                    filePart.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
                    filePart.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
                    filePart.Headers.ContentDisposition.FileName = fileName;

                    content.Add(jsonPart);
                    content.Add(filePart);

                    return content;
                }    
    private static HttpContent CreateMultipartContent(JToken json, string markupText, string fileName)
                        {
                            MultipartContent content = new MultipartContent("form-data", Guid.NewGuid().ToString());

                            StringContent jsonPart = new StringContent(json.ToString());
                            jsonPart.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
                            jsonPart.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                            StringContent filePart = new StringContent(markupText);
                            filePart.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
                            filePart.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
                            filePar`enter code here`t.Headers.ContentDisposition.FileName = fileName;

                            content.Add(jsonPart);
                            content.Add(filePart);

                            return content;
                        }