DHL CreateShipmentOrder XML API - api

I'm trying to integrate the DHL CreateShipmentOrder API.
When I send the document prepared by DHL with the Soap UI program, it works correctly.
My code and the returned result are as follows.
When I contacted DHL, I could not reach the result. Can you help me ?
I'm trying to integrate the DHL CreateShipmentOrder API.
When I send the document prepared by DHL with the Soap UI program, it works correctly.
My code and the returned result are as follows.
When I contacted DHL, I could not reach the result. Can you help me ?
My Code;
public static void Main()
{
// Create Web request to get title elements
var serviceUrl = "https://cig.dhl.de/services/production/soap";
HttpWebResponse response = null;
try
{
String sPayload = String.Format(#"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:cis='http://dhl.de/webservice/cisbase' xmlns:ns='http://dhl.de/webservices/businesscustomershipping/3.0'>
<soapenv:Header>
<cis:Authentification>
<cis:user>*****</cis:user>
<cis:signature>*******</cis:signature>
</cis:Authentification>
</soapenv:Header>
<soapenv:Body>
<ns:CreateShipmentOrderRequest>
<ns:Version>
<majorRelease>3</majorRelease>
<minorRelease>1</minorRelease>
</ns:Version>
<ShipmentOrder>
<sequenceNumber/>
<Shipment>
<ShipmentDetails>
<product>V01PAK</product>
<cis:accountNumber>********</cis:accountNumber>
<customerReference>Ref. 123456</customerReference>
<shipmentDate>2022-01-06</shipmentDate>
<ShipmentItem>
<weightInKG>5</weightInKG>
<lengthInCM>60</lengthInCM>
<widthInCM>30</widthInCM>
<heightInCM>15</heightInCM>
</ShipmentItem>
<Notification> <recipientEmailAddress>empfaenger#test.de</recipientEmailAddress>
</Notification>
</ShipmentDetails>
<Shipper>
<Name>
<cis:name1>Absender Zeile 1</cis:name1>
<cis:name2>Absender Zeile 2</cis:name2>
<cis:name3>Absender Zeile 3</cis:name3>
</Name>
<Address>
<cis:streetName>Vegesacker Heerstr.111</cis:streetName>
<cis:zip>28757</cis:zip>
<cis:city>Bremen</cis:city>
<cis:Origin>
<cis:country/>
<cis:countryISOCode>DE</cis:countryISOCode>
</cis:Origin>
</Address>
<Communication>
<!--Optional:-->
<cis:phone>+49421987654321</cis:phone>
<cis:email>absender#test.de</cis:email>
<!--Optional:-->
<cis:contactPerson>Kontaktperson Absender</cis:contactPerson>
</Communication>
</Shipper>
<Receiver>
<cis:name1>Empfänger Zeile 1</cis:name1>
<Address>
<cis:name2>Empfänger Zeile 2</cis:name2>
<cis:name3>Empfänger Zeile 3</cis:name3>
<cis:streetName>An der Weide 50a</cis:streetName>
<cis:zip>28195</cis:zip>
<cis:city>Bremen</cis:city>
<cis:Origin>
<cis:country/>
<cis:countryISOCode>DE</cis:countryISOCode>
</cis:Origin>
</Address>
<Communication>
<cis:phone>+49421123456789</cis:phone>
<cis:email>empfaenger#test.de</cis:email>
<cis:contactPerson>Kontaktperson Empfänger</cis:contactPerson>
</Communication>
</Receiver>
</Shipment>
<PrintOnlyIfCodeable active='1'/>
</ShipmentOrder>
<labelResponseType>URL</labelResponseType>
<combinedPrinting>0</combinedPrinting>
</ns:CreateShipmentOrderRequest>
</soapenv:Body>
</soapenv:Envelope>");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(serviceUrl) as HttpWebRequest;
webRequest.ContentType = "text/xml;charset=utf-8";
webRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("******:*****"));
webRequest.Method = "POST";
using (var sw = new StreamWriter(webRequest.GetRequestStream()))
{
sw.Write(sPayload);
sw.Close();
}
response = (HttpWebResponse) webRequest.GetResponse();
}
catch (WebException ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
finally
{
if (response != null)
Console.WriteLine("Http status = " + response.StatusCode + " - " + response.StatusDescription);
}
if( response != null && response.StatusDescription == "OK" ) {
Console.WriteLine("Successfull");
}
Console.WriteLine(DateTime.Now.ToString());
}
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>SECURITY_VIOLATION</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>

In order to communicate with DHL, it is imperative to use the DHL WSDL files and accesses. (Download at https://developer.dhl.de/)
Benjamin Müller gives the answer to your question under the following link. It is best to use the latest WSDL from DHL, a few objects (actually only names) still have to be adjusted.
Java WSDL DHL Classes
The two lines below the following line must be used, otherwise the authentication will not work.
// overwrite BasicAuth Username and Password
This is the only way DHL will not reject the request with "SECURITY_VIOLATION".
All other ways are not approved by DHL and lead to an error message.

Related

Rest API return response XML format, but same xml not get in result by using httpclient

I have created web api which return xml format response. like below
<TXLife xmlns="http://ACORD.org/Standards/Life/2">
<TXLifeResponse>
<TransRefGUID>61ec7f39-5744-410e-b601-dcd89d8d6f27</TransRefGUID>
<TransType tc="510">Form Instance Update</TransType>
<TransSubType tc="1022500310">Annuity Application for Mani ManiM</TransSubType>
<TransExeDate>2016-08-25-04:00</TransExeDate>
<TransExeTime>16:36:41.157-04:00</TransExeTime>
<TransMode tc="2">Original</TransMode>
<NoResponseOK tc="0"/>
<TransResult>
<ResultCode tc="3">Received Pending</ResultCode>
</TransResult>
But when call API using httpclient, I received response but response data is not same as above instead i got decode of special character.
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"><?
xml version="1.0" encoding="utf-8"?>
<TXLife xmlns:acord="http://ACORD.org/Standards/Life/2">
<TXLifeResponse>
<TransRefGUID>dd8973e3-ac03-4690-908b-
65da3d6a770f</TransRefGUID>
<TransType tc="510">Form Instance Update</TransType>
<TransSubType tc="1022500310">
Annuity Application for SUZANNE M PERSON</TransSubType>
<TransExeDate>2020-08-17</TransExeDate>
<TransExeTime>15:28:24Z</TransExeTime>
<TransMode tc="2">Original</TransMode>
<NoResponseOK tc="0" />
<TransResult>
<ResultCode tc="3">Received Pendinge</ResultCode>
</TransResult>
</TXLifeResponse>
</TXLife></string>
I am using below code to call API
string response = string.Empty;
using (var client = new HttpClient())
{
client.BaseAddress = parameters.DestinationUri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var responseTask = client.PostAsXmlAsync(parameters.DestinationUri, request);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
response = result.Content.ReadAsStringAsync().Result;
}
Resolved. I fixed by just in API response. I return HttpResponseMessage instead of return string object. Changes in API like below
string response = "response string info";
return new HttpResponseMessage()
{
Content = new StringContent(response, Encoding.UTF8, "application/xml")
};

Nested elements with List is null with ResponseEntity in Spring

I have a REST Controller as follows using Spring boot 1.3.5 and Java 8. This works perfect while testing with Advanced REST Client (ARC) Utility - send xml request and returns the expected xml response as shown right below this controller code.
#RestController
#EnableAutoConfiguration
#RequestMapping("/rateQuote")
public class RateQuoteController {
#Autowired
private RateQuotingService rateQuotingService;
#RequestMapping(method = RequestMethod.POST, consumes = {"application/json","application/xml"}, produces = {"application/json","application/xml"})
public ResponseEntity<RateQuoteDto> getRateQuote(#RequestBody RESTRequestDto request){
RateQuoteDto rateQuoteDto = rateQuotingService.getRateQuote(request.getStateCode(), request.getZipCode(), request.getClient(), request.getThreshold(),
benefit,request.getLob(), localEffectiveDate);
return (new ResponseEntity<>(rateQuoteDto, HttpStatus.OK));
}
}
Request with ARC-
url - http://localhost:8080/rateQuote
Method - POST
Headers -
Content-Type: application/xml
Accept: application/xml
Request Body -
<request>
<stateCode>NY</stateCode>
<zipCode>10005</zipCode>
<client>BMG</client>
<threshold>1000</threshold>
<lob>PDI</lob>
<benefitLevel>15000</benefitLevel>
<effectiveDate>2016-01-01</effectiveDate>
</request
Response -
<?xml version="1.0" encoding="UTF-8"?>
<rateQuote>
<status>Approve</status>
<message>Quote is successfully retrieved.</message>
<quote>
<threshold1 amount="1000">
<benefits>
<benefitLevel amount="15000">
<annualPremium>990.00</annualPremium>
<semiAnnualPremium>440.00</semiAnnualPremium>
<quaterlyPremium>200.00</quaterlyPremium>
<monthlyPremium>77.00</monthlyPremium>
</benefitLevel>
</benefits>
</threshold1>
</quote>
</rateQuote>
So far so good. However, I have an issue with response when call is made grammatically.And the issue is that the most of the response's nodes are null as shown below:
#Test
public void getQuote()throws Exception{
RestTemplate template = new RestTemplate();
//RESTRequestDto is JAXB decorated
RESTRequestDto body = new RESTRequestDto();
body.setStateCode("NY");
body.setZipCode("10005");
body.setClient("BMG");
body.setThreshold("1000");
body.setLob("PDI");
body.setBenefitLevel("15000");
body.setEffectiveDate(DateUtils.createDate("2016-01-01", "yyyy-MM-dd"));
RequestEntity<RESTRequestDto> request = RequestEntity.post(new URI("http://localhost:8080/rateQuote"))
.accept(MediaType.APPLICATION_XML).contentType(MediaType.APPLICATION_XML).body(body);
ResponseEntity<RateQuoteDto> response = template.exchange(request, RateQuoteDto.class);
RateQuoteDto rateQuote = response.getBody();
System.out.println(rateQuote);
}
Response -
RateQuoteDto{status=Approve, message=Quote is successfully retrieved., zipCode=null, clientId=null, quote=QuoteDto{threshold1=ThresholdDto{amount=1000, benefitLevelLst=null}}}
However, changing the Media Type to JSON works as shown below:
RequestEntity<RESTRequestDto> request = RequestEntity.post(new URI("http://localhost:8080/rateQuote"))
.accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).body(body);
Response -
RateQuoteDto{status=Approve, message=Quote is successfully retrieved., zipCode=10005, clientId=BMG, quote=QuoteDto{threshold1=ThresholdDto{amount=1000, benefitLevelLst=[BenefitDto{amount=15000, annualPremium=990.00, semiAnnualPremium=440.00, quaterlyPremium=200.00, monthlyPremium=77.00}]}}}
Observation -
As shown below, the ist benefitLevelLst is not bound with MediaType.XML returning null value show above but works just fine with MediaType.JSON. Any idea as to why?
public class ThresholdDto {
#XmlAttribute
private String amount;
#XmlElementWrapper(name = "benefits")
#XmlElement(name = "benefitLevel")
private List<BenefitDto> benefitLevelLst;
. . .
}

SMS integration web api consume by XML via HTTP RAW POST in c#.net

I need to integrate send sms api using like this URL. but I am getting the message XML is incorrect format.
http://<url>/action?application=msg&action=sendmsg&responsetype=xml
I am sending XML code like this
<data>
<phone> 1234567890 </phone>
<api_key 1234567890 </api_key>
<message_body> This is message text </message_body>
</data>
My code is
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create(#"http:\\domain.com\page.asp");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data,0,data.Length);
}
HttpWebResponse response = (HttpWebResponse)HttpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Please suggest how to resolve.strong text
Looks like just a typo.
Add > to end of the front api_key and the balance XML needs will work.

Upload File to Quickbooks online with IDS V3

I would like to upload a file to QuickBooks Online using IDS V3.
I followed the steps described here
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/020_key_concepts/attachments.
Here is my source code
URL url = new URL("https://quickbooks.api.intuit.com/v3/company/My_company_ID/upload");
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.setDoOutput(true);
request.setRequestMethod("POST");
HttpParameters para = new HttpParameters();
//String status = URLEncoder.encode("中 文","utf-8").replaceAll("\\+", "%20");
//para.put("status", status);
String boundary = "---------------------------37531613912423";
//String content = "--"+boundary+"\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";
String pic = "\r\n--"+boundary+"\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"postpic.gif\"\r\nContent-Type: image/gif\r\n\r\n";
byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();
File f = new File("/Users/cnanfack/Documents/oml_map1.gif");
FileInputStream stream = new FileInputStream(f);
byte[] file = new byte[(int)f.length()];
stream.read(file);
String lineEnd = "\r\n";
String header = "Content-Disposition: form-data; name=\"file_metadata_0\""+lineEnd
+"Content-Type: application/xml; charset=UTF-8"+lineEnd
+"Content-Transfer-Encoding: 8bit"+lineEnd;
String attachable = header+"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Attachable xmlns=\"http://schema.intuit.com/finance/v3\" domain=\"QBO\" sparse=\"false\">"
+"<EntityRef type=\"Bill\">285</EntityRef>"
+"<Size>4099</Size>"
+"<ContentType>image/gif</ContentType>"
+"<FileName>postpic.gif</FileName>"
+"</Attachable>";
request.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
//request.setRequestProperty("Content-Length", String.valueOf(boundary.getBytes().length+"test".getBytes().length+pic.getBytes().length+f.length()+end_data.length));
//consumer.setAdditionalParameters(para);
consumer.sign(request);
OutputStream ot = request.getOutputStream();
ot.write(end_data);
ot.write(attachable.getBytes());
ot.write(end_data);
//ot.write(status.getBytes());
ot.write(pic.getBytes());
ot.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
ot.write(file);
ot.write(end_data);
ot.flush();
ot.close();
System.err.println("Sending request...");
request.connect();
System.err.println("Response: " + request.getResponseCode() + " "
+ request.getResponseMessage());
BufferedReader reader =new BufferedReader(new InputStreamReader(request.getInputStream()));
String b = null;
while((b = reader.readLine())!=null){
System.err.println(b);
}
The returned result:
Response: 200 OK
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2013-11-10T20:24:27.823-08:00"/>
But I don't see the file on Quickbooks Online.
Maybe I miss something. Can someone help me?
Thank you in advance
I had tried this Upload endpoint call using Java Devkit. It is working fine. PFB details.
- Request URI : https://quickbooks.api.intuit.com/v3/company/688779980/upload? Http
- Method : POST Content-Disposition: form-data; name="file_metadata_2bddf"
- Content-Type: application/xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Attachable xmlns="http://schema.intuit.com/finance/v3">
<FileName>images.jpg</FileName>
<ContentType>image/jpeg</ContentType>
<Lat>25.293112341223</Lat>
<Long>-21.3253249834</Long>
<PlaceName>Fake Place</PlaceName>
<Note>Attachable note 900a49e1</Note>
<Tag>Attachable tag 900a49e1</Tag>
</Attachable>
Response XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2013-11-12T05:58:25.296-08:00">
<AttachableResponse>
<Attachable domain="QBO" sparse="false">
<Id>100000000000543524</Id>
<SyncToken>0</SyncToken>
<MetaData>
<CreateTime>2013-11-12T05:58:26-08:00</CreateTime>
<LastUpdatedTime>2013-11-12T05:58:26-08:00</LastUpdatedTime>
</MetaData>
<FileName>images.jpg</FileName>
<FileAccessUri>/v3/company/688779980/download/100000000000543524</FileAccessUri>
<TempDownloadUri>https://intuit-qbo-prod-19.s3.amazonaws.com/688779980%2Fattachments%2Fimages-1384264705362.jpg?Expires=1384265606&AWSAccessKeyId=AKIAJEXDXKNYCBUNCCCQ&Signature=ESZPzeO%2B5YWxw8VOWMVMBRnvIdw%3D</TempDownloadUri>
<Size>58616</Size>
<ContentType>image/jpeg</ContentType>
<Lat>25.293112341223</Lat>
<Long>-21.3253249834</Long>
<PlaceName>Fake Place</PlaceName>
<Note>Attachable note 8219e79a</Note>
<Tag>Attachable tag 8219e79a</Tag>
<ThumbnailFileAccessUri>/v3/company/688779980/attachable-thumbnail/100000000000543524</ThumbnailFileAccessUri>
</Attachable>
</AttachableResponse>
</IntuitResponse>
From the ThumnailFileAccessUri property I got the following attachment URI which I had used for Download endpoint.
/v3/company/688779980/attachable-thumbnail/100000000000543524
Download Endpoint(GET)-
https://quickbooks.api.intuit.com/v3/company/688779980/download/100000000000543521
JAVA/.Net SDK download link - https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits
Hope it will be useful.
EDIT- Adding Java code snippet
public static void executeUploadForImageFilePoc(DataService service) throws ParseException, FMSException, FileNotFoundException {
System.out.println("executeUploadForImageFile");
String uuid = UUID.randomUUID().toString().substring(0, 8);
Attachable attachable1 = new Attachable();
//attachable.setSize(new Long("34234"));
attachable1.setLat("25.293112341223");
attachable1.setLong("-21.3253249834");
attachable1.setPlaceName("Fake Place");
attachable1.setNote("Attachable note " + uuid);
attachable1.setTag("Attachable tag " + uuid);
Attachable attachable = attachable1;
attachable.setFileName("images.jpg");
attachable.setContentType("image/jpeg");
File file = new File("C:\\images_new.jpg");
InputStream in = new FileInputStream(file);
//Upload endpoint call
Attachable attachableOutput = service.upload(attachable, in);
//Check return XML
attachable.getFileAccessUri();
System.out.println(attachableOutput.getFileAccessUri());
System.out.println(attachableOutput.getFileName());
//Download endpoint call
InputStream output = service.download(attachableOutput);
try {
BufferedImage bImageFromConvert = ImageIO.read(output);
ImageIO.write(bImageFromConvert, "jpg", new File("C:\\images_new_manas.jpg"));
} catch (IOException e) {
throw new FMSException("Error while reading the upload file.", e);
}
}
Thanks
I have a working code in dotnet. See if it works for you:
DataService.DataService commonServiceQBO= new DataService.DataService(qboContextoAuth);
string imagePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "\\", "Services\\Resource\\image.jpg");
System.IO.FileInfo file = new System.IO.FileInfo(imagePath);
Attachable attachable = new Attachable();
attachable.AttachableRef = new AttachableRef[1];
attachable.AttachableRef[0].EntityRef = new ReferenceType();
attachable.AttachableRef[0].EntityRef.type = "Bill";
attachable.AttachableRef[0].EntityRef.Value = "12";
attachable.Lat = "25.293112341223";
attachable.Long = "-21.3253249834";
attachable.PlaceName = "Fake Place";
attachable.Note = "Attachable note123 ";
attachable.Tag = "Attachable tag123 ";
using (System.IO.FileStream fs = file.OpenRead())
{
attachable.ContentType = "image/jpeg";
attachable.FileName = file.Name;
Attachable attachableUploaded = commonServiceQBO.Upload(attachable, fs);
}
For download use:
byte[] responseByte = service.Download(attachableUploaded);

force.com streaming API

I am trying the Force.com Streaming API demo and I get the following error:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sf="urn:fault.partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body><soapenv:Fault>
<faultcode>UNKNOWN_EXCEPTION</faultcode>
<faultstring>UNKNOWN_EXCEPTION: Element type "soapenv:Envelope" must be followed by either attribute specifications, ">" or "/>". </faultstring>
<detail>
<sf:UnexpectedErrorFault xsi:type="sf:UnexpectedErrorFault">
<sf:exceptionCode>UNKNOWN_EXCEPTION</sf:exceptionCode>
<sf:exceptionMessage>Element type "soapenv:Envelope" must be followed by either attribute specifications, ">" or "/>".</sf:exceptionMessage>
</sf:UnexpectedErrorFault>
</detail>
</soapenv:Fault></soapenv:Body>
</soapenv:Envelope>
Line 22 has a misplaced double quote that is not caught by your compiler.
Replace this code:
private static final String ENV_START =
"
"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'
+ "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xmlns:urn='urn:partner.soap.sforce.com'><soapenv:Body>";
With this code:
private static final String ENV_START =
"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'"
+ "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xmlns:urn='urn:partner.soap.sforce.com'><soapenv:Body>";