访问接⼝返回400错误
对于400错误,出现的原因⼤概有⼏个。
⼀:第⼀步确认postmen中发送的数据类型是json。⽐如Headers中Content-Type类型是application/json;或是前端代码Ajax中添加:contentType:
'application/json;charset=UTF-8';
⼆:确认postmen中发送的数据格式是否正确。postmen中经常有⼈有漏写⼀对“{}“或是缺少逗号,引号,冒号的⼩问,好在postmen会⾃动报错提⽰;⽽在前端中你必须重新
包装传⼊参数为JSON型。使⽤JSON.stringify(params)将params参数重新包装;
三:检查参数的类型是否⼀⼀对应;
四:对接接⼝时,有可能参数的值不匹配,⽐如说地址不符合实际要求时,可能返回400错误提⽰;
本⼈遇到的属于第四种情况,在检查完预报参数类型和数据格式之后,依然报400错误,后来发现是对⽅地址有验证,有实际的报错信息,但是我们得到的是400错误,怎么解
决呢?
下⾯贴代码:
1.预报参数
//创建货件,设置请求参数
public ShipmentRequest SetRequest(Package package, PBUSPSConfig Config)
{
var model = new ShipmentRequest();
string[] address1 = new string[] { package.SenderAddress.Address };//发件地址
string[] address2 = new string[] { !string.IsNullOrWhiteSpace(package.ShippingAddress.Address)? package.ShippingAddress.Address:"", !string.IsNullOrWhiteSpace(package.ShippingAddress.A foreach (var packageInfo in package.PackageInfos)
{
//1磅等于453.59克
double weights = Convert.ToDouble(packageInfo.Weight * 1000);
//常衡盎司:重量单位。整体缩写为oz.av。 1盎司 = 28.350克
decimal Weight = Convert.ToDecimal(weights / 28.350);//重量转盎司
model.fromAddress = new Address()
{
company = package.SenderAddress.CompanyName,
name = package.SenderAddress.FirstName,
phone = !string.IsNullOrWhiteSpace(package.SenderAddress.PhoneNumber) ? package.SenderAddress.PhoneNumber : package.SenderAddress.Mobile,
email = package.SenderAddress.Email,
residential = false,
addressLines = address1,
cityTown = package.SenderAddress.City,
stateProvince = package.SenderAddress.Province,
postalCode = package.SenderAddress.PostalCode,
countryCode = package.SenderAddress.CountryCode,
};
{
company = package.ShippingAddress.CompanyName,
name = package.ShippingAddress.FirstName,
phone =!string.IsNullOrWhiteSpace(package.ShippingAddress.PhoneNumber)? package.ShippingAddress.PhoneNumber: package.ShippingAddress.Mobile,
email = "",
residential = false,
addressLines = address2,
cityTown = package.ShippingAddress.City,
stateProvince = !string.IsNullOrWhiteSpace(localityProvincia) ? localityProvincia : package.ShippingAddress.Province,
postalCode = package.ShippingAddress.PostalCode,
countryCode = package.ShippingAddress.CountryCode,
};
model.parcel = new parcel()
{
weight = new Weight()
{
unitOfMeasurement = "OZ",//度量单位
weight = Weight,//包裹的重量
},
dimension = new Dimension()
{
unitOfMeasurement = "IN",
length=10,
width=4,
height=6,
irregularParcelGirth = "20"//将此设置为不规则包裹的周长。周长是⾼度和宽度之和的两倍:
}
};
model.rates = new rates[] {
new rates()
{
carrier="NEWGISTICS",
serviceId="PRCLSEL",
parcelType="PKG",
specialServices= new SpecialServices[]{
new SpecialServices()
{
specialServiceId="DelCon"
},
new SpecialServices()
{
specialServiceId="NOTIFICATIONS",
inputParameters=new InputParameters[] {
new InputParameters(){
name="RECIPIENT_NOTIFICATION_TYPE",
value="ON_DELIVER"
},
new InputParameters(){
name="RECIPIENT_NOTIFICATION_EMAIL",
value="widgets@example"
}
}
}
}
}
};
model.documents = new documents[] {
new documents(){
type="SHIPPING_LABEL",
contentType="URL",
size="DOC_4X6",
fileFormat="PDF",
}
};
model.shipmentOptions = new shipmentOptions[] {
new shipmentOptions(){
name="SHIPPER_ID",
value=Config.ShipperId,
},
new shipmentOptions(){
name="IS_RECTANGULAR",
value="false",
},
new shipmentOptions(){
name="CLIENT_FACILITY_ID",
value=Config.ClientFacilityId,
},
new shipmentOptions(){
name="CARRIER_FACILITY_ID",
value=Config.CarrierFacilityId,
},
new shipmentOptions(){
name="NON_DELIVERY_OPTION",
//⼤于⼀磅的包裹,就是这样的值ChangeServiceRequested,  ⼩于⼀磅的,就空着,不填
value=weights > 453.59?"ChangeServiceRequested":"",
}
};
}
return model;
}
View Code
2.访问接⼝返回值
1//创建货件,取返回参数  ShipmentResponse
2public string GetResponse(ShipmentRequest ShipmentRequest, string access_token, PBUSPSConfig config)
3        {
4var stopWatch = new Stopwatch();
5var Url = config.ForecastUrl + "/shippingservices/v1/shipments?includeDeliveryCommitment=true";
6var TransactionId = GenerateStringID();
7            HttpWebRequest request = null;
8if (Url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
9            {
10                request = WebRequest.Create(Url) as HttpWebRequest;
11                request.ProtocolVersion = HttpVersion.Version11;
12                request.KeepAlive = false;
13            }
14else
write的返回值15            {
16                request = (HttpWebRequest)WebRequest.Create(Url);
17            }
18            request.Method = "POST";
19            request.ContentType = "application/json";
20            request.Accept = "application/json";
21            request.AllowAutoRedirect = true;
22            request.Headers.Add("Authorization", "Bearer " + access_token);
23            request.Headers.Add("X-PB-TransactionId", TransactionId);
24            Stream myRequestStream = request.GetRequestStream();
25            StreamWriter myStreamWriter =
26new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
27var Ship = JsonConvert.SerializeObject(ShipmentRequest);
28byte[] data = Encoding.UTF8.GetBytes(Ship);
29            SetCertificatePolicy();
30using (Stream requestStream = request.GetRequestStream())
31            {
32                requestStream.Write(data, 0, data.Length);
33            }
34using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
35            {
36                Stream myResponseStream = response.GetResponseStream();
37                StreamWriter myStreamReader =
38new StreamWriter(myResponseStream, Encoding.GetEncoding("utf-8"));
39using (StreamReader reader = new StreamReader(response.GetResponseStream()))
40                {
41return reader.ReadToEnd();
42                }
43            }
44        }
View Code
3.处理400错误 (catch)
1  HttpWebResponse response = (HttpWebResponse)ex.Response;
2var message = "";
3if (response?.StatusCode == HttpStatusCode.BadRequest)
4                {
5using (Stream data = response.GetResponseStream())
6                    {
7using (StreamReader reader = new StreamReader(data))
8                        {
9string text = reader.ReadToEnd();
10var jo = JsonConvert.DeserializeObject<List<Errors>>(text);
11var json = jo.First();
12                            message = "服务商:" + ssage;
13                        }
14                    }
15                }
4.在得到具体的返回值之后,发现返回值是⼀个以中括号开头和结尾的字符串类型,添加⼀个实体类,映射返回值
1public class Errors {
2        [JsonProperty("errorCode")]
3public string errorCode { get; set; }
4        [JsonProperty("message")]
5public string message { get; set; }
6        [JsonProperty("parameters")]
7public string[] parameters { get; set; }
8    }
View Code
以上就是处理400参数的解决⽅案。
5.“基础连接已经关闭”的错误
1private static void SetCertificatePolicy()
2        {
3            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
4// 这⾥设置了协议类型。
5            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;// SecurityProtocolType.Tls1.2;
6            ServicePointManager.CheckCertificateRevocationList = true;
7            ServicePointManager.DefaultConnectionLimit = 100;
8            ServicePointManager.Expect100Continue = false;
9        }
10private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain ch
ain, SslPolicyErrors errors)
11        {
12return true; //总是接受
13        }
View Code

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。