Am developing simple rest webservices with jersey frame work. Written @POST method which consumes and produces both { MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML
}. Using chrome Advance rest client to invoke the web services. Webservices is working as expected for below application/json request
{"noSave": "Save", "dateCre":"14/12/2014"}
but getting 400 bad request for the below appliation/xml request
<?xml version="1.0" encoding="UTF-8">
<noSave>Save</noSave>
<dateCre>14/12/2014</dateCre>
there are no compilation errors in the code. Any help in resolving the below issue is appreciated. below is the code i have written
request object:
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Creation", propOrder = {
})
public class Creation {
@XmlElement(required = true)
protected String noSave;
@XmlElement(required = true)
protected String dateCre;
public String getNoSave() {
return noSave;
}
public void setNoSave(String value) {
this.noSave = value;
}
public String getDateCre() {
return dateCre;
}
public void setDateCre(String value) {
this.dateCre = value;
}
}
response object:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MyResponse", propOrder = {
})
public class MyResponse {
@XmlElement(required = true)
protected String resString;
public String getResString() {
return resString;
}
public void setResString(String value) {
this.resString = value;
}
}
rest webservice:
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/create")
public class CreateRequest {
@POST
@Produces({ MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createReq( @Valid Creation request)
{
System.out.println(" Request "+request.getNoSave());
MyResponse result = new MyResponse();
result.setResString(" Created with Number 123");
return Response.ok(result).build();
}
}
Below is the error am getting in the chrome rest client
Status 400 Bad Request. Loading time: 4250
Request headers User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Content-Type: application/xml
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Response headers Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 990
Date: Tue, 13 Jan 2015 13:53:11 GMT
Connection: close
i also tried below piece of code
@XmlRootElement(name="Creation")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Creation", propOrder = {
})
public class Creation {
and below xml request. But getting the same error
<?xml version="1.0" encoding="UTF-8">
<Creation>
<noSave>NoSave</noSave>
<dateCre>14/12/2014</dateCre>
</Creation>
below error in the logs is displayed
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Creation"). Expected elements are <{http://check.com/rrs}Creation>
I have a simple WCF POST that posts a simple XML to the service.
This is the service contract.
[ServiceContract]
public interface ITest
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "PostTest")]
Stream PostTest(Stream testInfo);
}
And the configuration, nothing fancy.
<system.serviceModel>
<services>
<service name="T.Test" behaviorConfiguration="ServiceBehaviour">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address ="" binding="webHttpBinding" contract="T.ITest" behaviorConfiguration="web">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
Everything works when I test it from a simple client as long as I don’t mention the content type.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = «text/xml; charset=utf-8»;
var xmlDoc = new XmlDocument { XmlResolver = null };
xmlDoc.Load("../../PostData.xml");
string sXml = xmlDoc.InnerXml;
Console.Write(sXml + Environment.NewLine + Environment.NewLine);
req.ContentLength = sXml.Length;
var sw = new StreamWriter(req.GetRequestStream());
sw.Write(sXml);
sw.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
After some research I understand this is a compatibility issue between soap 1.1 vs soap 1.2. But how do I fix this on server side?
Ошибки
При работе с АПИ сервер может выдать сообщение об ошибке errors
с кодом 4xx
Код | Описание | Коментарий |
---|---|---|
400 | Неверный запрос | Причину ошибки смотрите в теле ответа |
401 | Неверный ключ авторизации | Вы используете не верный ключ дочтупа к АПИ |
403 | Доступ запрещен | У вас нет прав доступа к АПИ. Обратитесь в менеджеру для разьяснения причины отсутствия прав |
404 | Ресурс не найден | Вы обращаетесь по нерпавильному url. Возможно вы опечатались. |
406 | Запрос не приемлем | Параметры запроса не заданны или некорректны |
429 | Слишком много запросов | Превышено допустимое число запросов в секунду с одного ip-адреса (5 запросов в секунду) |
Примеры ошибок
400 JSON
{ "errors":{ "base":"Ваша корзина пуста!" } }
400 XML
<?xml version="1.0" encoding="UTF-8"?> <errors> <base>Ваша корзина пуста!</base> </errors>
401 JSON
{ "errors":{ "api_key":"Неверный ключ авторизации" } }
401 XML
<?xml version="1.0" encoding="UTF-8"?> <errors> <api_key>Неверный ключ авторизации</api_key> </errors>
403 JSON
{ "errors":{ "permission":"Доступ запрещен" } }
403 XML
<?xml version="1.0" encoding="UTF-8"?> <errors> <permission>Доступ запрещен</permission> </errors>
404 JSON
{ "errors":{ "source":"Ресурс не найден" } }
404 XML
<?xml version="1.0" encoding="UTF-8"?> <errors> <source>Ресурс не найден</source> </errors>
406 JSON
{ "errors":{ "request":"Параметры запроса не заданны или некорректны" } }
406 XML
<?xml version="1.0" encoding="UTF-8"?> <errors> <request>Параметры запроса не заданны или некорректны</source> </errors>
Пытаю отправить XML POST запросом по API в CDEK выдает ошибку: 400 Bad Request, служба поддержки помочь не захотела, сказали только что xml составлен правильно
$request = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<DeliveryRequest
Number="0000033876WO"
Date="2019-04-05T10:01:15+00:00"
Account="2JewP7QZL****3a3qT1z8NCbIIbKAw2"
Secure="f6b6059bb333ec****f5446457f2"
OrderCount="1">
<Order Number="12345" SendCityPostCode="350000" RecCityPostCode="350000" RecipientName="Герусов Александр Валерьевич" RecipientEmail="gerusov14@mail.ru" Phone="89615096005" TariffTypeCode="136" DeliveryRecipientCost="137" DeliveryRecipientVATRate="VATX" DeliveryRecipientVATSum="0" SellerName="ИП Волженин Е.Г." SellerAddress="Ленинградская обл, Всеволожский р-н, Пос. Лесное, дом № 18, кв.6">
<Address PvzCode="KSD5"/>
<Package Number="1" BarCode="krd61927-1" Weight="1000">
<Item WareKey="158308" Cost="790" Payment="790" PaymentVATRate="VATX" PaymentVATSum="0" Weight="1000" Amount="1" Comment="Кронштейн для телевизора Ultramounts UM 814F черный"/>
</Package>
</Order>
</DeliveryRequest>
XML;
$host_api = 'https://integration.cdek.ru/new_orders.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $host_api);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array('Content-Type: text/xml; charset=utf-8',
'Content-Length: '. strlen($request)));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, [
'xml_request' => $request
]);
$response = curl_exec($curl);
if ($response === false) {
echo "cURL Error: " . curl_error($curl);
}
curl_close($curl);
echo "<pre>";
print_r($response);
echo "</pre>";
I am sending a request to external API from my application using HttpWebRequest and HttpWebResponse.
Whenever there is an error in XML request due to some wrong values passed in XML nodes, then there is a 400 Bad request error response and the error message is «There is an error in XML document (51, 14)». The problem is if there is an error in request XML, the response XML should display the error message with correct line number. but I am receiving an error message with incorrect line number and it is always «There is an error in XML document (1, 1254)». There is actually no error at line 1. Due to this issue, I have no chance to point to the error when troubleshooting.
Can you help how do I get Response with the correct line number in XML.
Thanks
What I have tried:
Below is my existing code in vb to send the request to API.
Dim Wreq As HttpWebRequest
Dim MyURI As String = String.Empty
Dim bytes() As Byte
Try
MyURI = p_strURL
Wreq = HttpWebRequest.Create(MyURI)
Wreq.Method = «POST»
bytes = System.Text.Encoding.UTF8.GetBytes(pi_strRequestXML)
Wreq.ContentLength = bytes.Length ‘pi_strRequestXML.Length
Wreq.ContentType = «application/x-www-form-urlencoded»
Wreq.KeepAlive = False
Wreq.Headers.Add(«Authorization», «bearer» + » » + strAccessToken)
Using OutputStream As StreamWriter = New StreamWriter(Wreq.GetRequestStream())
OutputStream.Write(pi_strRequestXML)
End Using
Using Wres As HttpWebResponse = Wreq.GetResponse()
Using loResponseStream As StreamReader = New StreamReader(Wres.GetResponseStream())
oResponse = loResponseStream.ReadToEnd()
End Using
End Using
Return oResponse
Catch e As WebException
Throw
Catch objSysEx As Exception
Throw
Finally
End Try
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900