调用FedEx运费报价API返回400状态码时反序列化对象失败的问题求助
调用FedEx运费报价API返回400状态码时反序列化对象失败的问题求助
我翻遍谷歌都没找到解决办法,只好来这儿求助了!
先贴一下我的核心代码:
try { response = client.PostAsync("", content).Result; // 阻塞调用!程序会在这里等待响应或超时 if (response.IsSuccessStatusCode) { var contents = response.Content.ReadAsStringAsync().Result; FxRateReturn = JsonConvert.DeserializeObject<FedExFreightQuoteAPI_inbound.Root>(contents); } else { var contents = response.Content.ReadAsStringAsync().Result; FxRateReturn = JsonConvert.DeserializeObject<FedExFreightQuoteAPI_inbound.Root>(contents); throw new Exception("Error retrurned by the API: \n" + response.StatusCode.ToString() + response.ReasonPhrase.ToString() + FxRateReturn.errors.FirstOrDefault().message); } return FxRateReturn; } catch (Exception ex) { throw new Exception(ex.Message, ex); }
现在问题出在else分支里:当response.IsSuccessStatusCode为false时,我尝试读取响应内容并反序列化,但总是失败。报错信息是:
ERROR: Unexpected character encountered while parsing value: . Path '', line 0, position 0.
我用Postman测试过同样的请求,接口返回的错误响应明明是标准的JSON格式,但用我的代码调用时,响应内容就变成了一堆奇怪的字符,根本不是JSON。我实在搞不懂哪里出问题了!
对了,再贴一下我的HttpClient相关声明代码,方便大家排查:
HttpClient client = new HttpClient(); client.BaseAddress = new Uri(APIURL + "/rate/v1/rates/quotes"); // 添加JSON格式的Accept头 client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", p_Token); var content = new StringContent(JsonConvert.SerializeObject(p_FedExOutbound), Encoding.UTF8, "application/json"); HttpResponseMessage response;
备注:内容来源于stack exchange,提问作者Be05x5
相关产品推荐
相关产品推荐

