2014-11-01 49 views
1

我做这将需要通过HTTP数据发布到URL的应用程序,下面是我如何上传数据的代码:出现InvalidOperationException在HTTP POST时抛出尝试创建HttpContent

using(System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { 
    //Initialize a HttpClient 
    client.BaseAddress = new Uri(strURL); 
    client.Timeout = new TimeSpan(0, 0, 60); 
    client.DefaultRequestHeaders.Accept.Clear(); 

    FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(convertNameValueCollectionToKeyValuePair(HttpUtility.ParseQueryString(objPostData.ToString()))); 
    //This is where I got stuck 
    System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<FormUrlEncodedContent> (formUrlEncodedContent, new System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter()); 


    using(System.Net.Http.HttpResponseMessage response = client.PostAsync(strAddr, content).Result) {} 
} 

protected static IEnumerable<KeyValuePair<string, string>> convertNameValueCollectionToKeyValuePair(NameValueCollection input) { 
    var values = new List<KeyValuePair<string, string>>(); 

    foreach(var key in input.AllKeys) { 
     values.Add(
     new KeyValuePair<string, string> (key, input[key])); 
    } 

    return values.AsEnumerable(); 
} 

代码运行顺利,直到它碰上了这样一行:

System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<FormUrlEncodedContent>(formUrlEncodedContent, new System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter()); 

例外The configured formatter 'System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter' cannot write an object of type 'FormUrlEncodedContent'.流动

有什么不好的代码?

回答

3

哦,我想通了......

我改变创建HttpContent ...

using(System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { 
    //Initialize a HttpClient 
    client.BaseAddress = new Uri(strURL); 
    client.Timeout = new TimeSpan(0, 0, 60); 
    client.DefaultRequestHeaders.Accept.Clear(); 

    //I changed this line. 
    System.Net.Http.HttpContent content = new System.Net.Http.FormUrlEncodedContent(convertNameValueCollectionToKeyValuePair(HttpUtility.ParseQueryString(objPostData.ToString())); 

    using(System.Net.Http.HttpResponseMessage response = client.PostAsync(strAddr, content).Result) {} 
} 
的方法
相关问题