C# 调用DHL查询预估运费的rest+json接口
本文不介绍原理,直接上代码
申请好username和password后开始接入:
首先创建参数实体:
ServiceHeader.cs
RequestedShipment.cs
Packages.cs
Billing.cs
测试环境接口:https://wsbexpress.dhl.com/rest/sndpt/RateRequest
private readonly string _baseURL;
private readonly string _username;
private readonly string _password;
public string LastJSONRequest
{
get;
set;
}
public string LastJSONResponse
{
get;
set;
}
public string LastHTTPRequest
{
get;
set;
}
public string LastHTTPResponse
{
get;
set;
}
public string LastRateQueryJSONRequest
{
get;
set;
}
public string LastRateQueryJSONResponse
{
get;
set;
}
public string LastRateQueryHTTPRequest
{
get;
set;
}
public string LastRateQueryHTTPResponse
{
get;
set;
}
public string LastShipJSONRequest
{
get;
set;
}
public string LastShipJSONResponse
{
get;
set;
}
public string LastShipHTTPRequest
{
get;
set;
}
public string LastShipHTTPResponse
{
get;
set;
}
public string LastNewPickupJSONRequest
{
get;
set;
}
public string LastNewPickupJSONResponse
{
get;
set;
}
public string LastNewPickupHTTPRequest
{
get;
set;
}
public string LastNewPickupHTTPResponse
{
get;
set;
}
public string LastDeletePickupJSONRequest
{
get;
set;
}
public string LastDeletePickupJSONResponse
{
get;
set;
}
public string LastDeletePickupHTTPRequest
{
get;
set;
}
public string LastDeletePickupHTTPResponse
{
get;
set;
}
public string LastTrackingJSONRequest
{
get;
set;
}
public string LastTrackingJSONResponse
{
get;
set;
}
public string LastTrackingHTTPRequest
{
get;
set;
}
public string LastTrackingHTTPResponse
{
get;
set;
}
public string LastEPoDJSONRequest
{
get;
set;
}
public string LastEPoDJSONResponse
{
get;
set;
}
public string LastEPoDHTTPRequest
{
get;
set;
}
public string LastEPoDHTTPResponse
{
get;
set;
}
public myapi(string username, string password, string baseUrl)
{
this._username = username;
this._password = password;
this._baseURL = baseUrl;
}
public RateQueryResponse RateQuery(RateQueryRequest rqr)
{
List<ValidationResult> list = Common.Validate<RateQueryRequest>(ref rqr);
bool flag = list.Any<ValidationResult>();
if (flag)
{
throw new MyDHLAPIValidationException(list);
}
this.LastJSONRequest = JsonConvert.SerializeObject(rqr, Formatting.Indented);
this.LastRateQueryJSONRequest = this.LastJSONRequest;
this.LastJSONResponse = this.SendRequestAndReceiveResponse(this.LastJSONRequest, "RateRequest");
this.LastRateQueryJSONResponse = this.LastJSONResponse;
this.LastRateQueryHTTPRequest = this.LastHTTPRequest;
this.LastRateQueryHTTPResponse = this.LastHTTPResponse;
RateQueryResponse result;
try
{
List<string> errors = new List<string>();
result = JsonConvert.DeserializeObject<RateQueryResponse>(this.LastJSONResponse, new JsonSerializerSettings
{
Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
}
});
}
catch
{
result = new RateQueryResponse();
}
return result;
}
public string SendRequestAndReceiveResponse(string req, string endpoint)
{
WebRequest webRequest = WebRequest.Create(new Uri(this._baseURL + "/" + endpoint));
webRequest.Credentials = new NetworkCredential(this._username, this._password);
webRequest.ContentType = "application/json";
webRequest.PreAuthenticate = true;
webRequest.UseDefaultCredentials = false;
webRequest.Method = "POST";
string str = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(this._username + ":" + this._password));
webRequest.Headers.Add("Authorization", "Basic " + str);
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
{
streamWriter.Write(req);
streamWriter.Flush();
streamWriter.Close();
}
string result = string.Empty;
try
{
WebResponse response = webRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (Exception)
{
throw;
}
return result;
}
调用方法:
private string apiUserName = 申请的username;
private string apiPassword = 申请的password;
private string apiBaseUrl = “https://wsbexpress.dhl.com/rest/sndpt”;
public string LastJSONResponse { get; private set; }
protected void Page_Load(object sender, EventArgs e)
{
var myDhlApi = new myapi(apiUserName, apiPassword, apiBaseUrl);
var resp = myDhlApi.RateQuery(new RateQueryRequest
{
RateRequest = new RateRequest
{
Request = new Request
{
ServiceHeader = new ServiceHeader
{
MessageReference = "TEST109311111112222222229876",
MessageTime = new DateTime(2019, 9, 3, 15, 7, 35),
Plugin = "MyDHL API_TEST",
PluginVersion = "1.0",
ShippingSystemPlatform = "MyDHL API_TEST",
ShippingSystemPlatformVersion = "1.0",
WebstorePlatform = "MyDHL API_TEST",
WebstorePlatformVersion = "1.0"
}
},
ClientDetails = null,
RequestedShipment = new RequestedShipment
{
DropOffType = Enums.DropOffType.RegularPickup,
NextBusinessDay = Enums.YesNo.Yes,
Ship = new Ship
{
Recipient = new MyDHLAPI_REST_Library.Objects.RateQuery.Address
{
City = "KAARST",
CountryCode = "DE",
PostalCode = "41564",
StreetLines = "Main Street"
},
Shipper = new MyDHLAPI_REST_Library.Objects.RateQuery.Address()
{
City = "Beijing",
CountryCode = "CN",
PostalCode = "100017",
StreetLines = "River House"
}
},
Packages = new Packages
{
RequestedPackages = new List<RequestedPackages>
{
new RequestedPackages
{
PieceNumber=1,
Weight = new Weight{ Value = 10},
Dimensions = new Dimensions{ Height = 1, Length = 3, Width = 2}
}
}
},
ShipTimestamp = new DateTime(2019, 9, 3, 19, 1, 0),
UnitOfMeasurement = Enums.UnitOfMeasurement.SI,
Content = Enums.ShipmentType.NonDocuments,
DeclaredValue = 100,
DeclaredValueCurrencyCode = "USD",
Billing = new Billing
{
BillingAccountNumber = "602965196",
ShipperAccountNumber = "602965196",
ShippingPaymentType = Enums.PaymentTypes.Shipper
},
PaymentInfo = Enums.TermsOfTrade.DAP,
NetworkTypeCode = Enums.NetworkTypeCode.All,
CustomerAgreementInd = Enums.YesNo.No,
ValidateReadyTime = Enums.YesNo.No
}
}
}); ;
var names = resp;
var namesss = JsonConvert.SerializeObject(resp);
Response.Write(JsonConvert.SerializeObject(resp));
}
传递的json参数格式:
{
“RateRequest”: {
“ClientDetails”: “”,
“Request”: {
“ServiceHeader”: {
“MessageTime”: “2019-09-03T15:07:35”,
“MessageReference”: “TEST109311111112222222229876”,
“WebstorePlatform”: “MyDHL API_TEST”,
“WebstorePlatformVersion”: “1.0”,
“ShippingSystemPlatform”: “MyDHL API_TEST”,
“ShippingSystemPlatformVersion”: “1.0”,
“PlugIn”: “MyDHL API_TEST”,
“PlugInVersion”: “1.0”
}
},
“RequestedShipment”: {
“DropOffType”: “REGULAR_PICKUP”,
“NextBusinessDay”: “Y”,
“ShipTimestamp”: “2019-09-03T19:01:00 G9T+08:00”,
“UnitOfMeasurement”: “SI”,
“Content”: “NON_DOCUMENTS”,
“DeclaredValue”: 100.0,
“DeclaredValueCurrecyCode”: “USD”,
“PaymentInfo”: “DAP”,
“RequestValueAddedServices”: “N”,
“NetworkTypeCode”: “AL”,
“CustomerAgreementInd”: “N”,
“ValidateReadyTime”: “N”,
“Ship”: {
“Shipper”: {
“StreetLines”: “River House”,
“City”: “BEIJING”,
“PostalCode”: “100017”,
“CountryCode”: “CN”
},
“Recipient”: {
“StreetLines”: “Main Street”,
“City”: “OSNABRUECK”,
“PostalCode”: “41564”,
“CountryCode”: “DE”
}
},
“Packages”: {
“RequestedPackages”: [{
“@number”: 0,
“Weight”: {
“Value”: 10.0
},
“Dimensions”: {
“Length”: 3.0,
“Width”: 2.0,
“Height”: 1.0
}
}]
},
“Billing”: {
“ShipperAccountNumber”: “602965196”,
“ShippingPaymentType”: “S”,
“BillingAccountNumber”: “602965196”
}
}
}
}
返回的json字符串:
{
“RateResponse”: {
“Provider”: [
{
“@code”: “DHL”,
“ServiceHeader”: {
“MessageTime”: “2020-07-04T10:20:41.094+00:00”,
“MessageReference”: “TEST109311111112222222229876”,
“ServiceInvocationID”: “20200704102041_b82c_b6c4a0a5-48d4-459f-9c11-073180add382”
},
“Notification”: [
{
“@code”: “0”,
“Message”: null
}
],
“Service”: {
“@type”: “Y”,
“TotalNet”: {
“Currency”: “CNY”,
“Amount”: 2000.81
},
“Charges”: {
“Currency”: “CNY”,
“Charge”: [
{
“ChargeType”: “EXPRESS 12:00”,
“ChargeAmount”: 1626.6
},
{
“ChargeCode”: “YK”,
“ChargeType”: “12:00 PREMIUM”,
“ChargeAmount”: 69.0
},
{
“ChargeCode”: “FF”,
“ChargeType”: “FUEL SURCHARGE”,
“ChargeAmount”: 305.21
}
]
},
“DeliveryTime”: “2019-09-09T12:00:00”,
“CutoffTime”: “2019-09-03T20:00:00”,
“NextBusinessDayInd”: “N”
}
}
]
}
}
示例代码下载:https://download.csdn.net/download/xmg1314/12576722