I try to make a restfull web service with Jersey. I would like to give a link in the response of that request :
GET /mac/ws/gtm HTTP/1.1
Host: localhost:8080
Accept: application/json
Cache-Control: no-cache
I want the response to be :
HTTP/1.1 200 OK
link: </dossiers>;rel=dossiers
{
"message": "Hello"
}
But the response is :
HTTP/1.1 200 OK
{
"message": "Hello"
}
The link is not produce !
Look my Gtm Resource :
#Component
#Path("/gtm")
public class GTmRessource
{
#GET
#Produces(MediaType.APPLICATION_JSON)
public GTm getJson()
{
GTm gtm = new GTm();
return gtm;
}
}
And my Gtm entity
#XmlRootElement()
#Link(value = #Ref(value = "/dossiers", method = "get"), rel = "dossiers")
public class GTm
{
String message = "Hello";
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
this.message = message;
}
}
What's wrong ?
Thanks for help.
By
See Declarative Hyperlinking: Configuration
You need to add the LinkFilter either programmatically:
resourceConfig.getContainerResponseFilters().add(LinkFilter.class);
or through web.xml
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.sun.jersey.server.linking.LinkFilter</param-value>
</init-param>
C:\>curl -i http://localhost:8080/gtm
HTTP/1.1 200 OK
Content-Type: application/json
Link: </dossiers>;rel=dossiers
Date: Thu, 04 Dec 2014 12:38:06 GMT
Transfer-Encoding: chunked
{"message":"Hello"}
Related
I am using below system properties:
System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
This is printing:
---[HTTP response - https://XXXXXXXXXXXXXXXXX/v1.0?wsdl - 200]---
null: HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Language: en-US
Content-Type: text/xml; charset=utf-8
Date: Tue, 09 Jan 2018 12:23:42 GMT
Keep-Alive: timeout=30, max=100
Transfer-Encoding: chunked
X-Frame-Options: SAMEORIGIN
X-Powered-By: Servlet/3.0
<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><sch:InquiryResponse xmlns:sch="http://XXXXXXXXXX/1.0"><sch:InquiryResponseHeader><sch:ClientID>XXXX</sch:ClientID><sch:ProductCode>PCS</sch:ProductCode><sch:SuccessCode>0</sch:SuccessCode><sch:Date>XX-XX-XXXX</sch:Date><sch:Time>17:53:28</sch:Time></sch:InquiryResponseHeader><sch:InquiryRequestInfo><sch:InquiryPurpose>05</sch:InquiryPurpose><sch:FirstName>Ajay</sch:FirstName><sch:LastName>XXXX</sch:LastName><sch:AddrLine1>XXXX</sch:AddrLine1><sch:State>MH</sch:State><sch:Postal>411014</sch:Postal><sch:DOB>1987-06-21</sch:DOB><sch:Id>XXXX</sch:Id><sch:MobilePhone>XXXX</sch:MobilePhone></sch:InquiryRequestInfo><sch:ReportData><sch:Error><sch:ErrorCode>E0021</sch:ErrorCode><sch:ErrorMsg>User ID does not exist for the given customer.</sch:ErrorMsg></sch:Error></sch:ReportData></sch:InquiryResponse></soapenv:Body></soapenv:Envelope>
How can I get XML data from above printing data?
I want to store that XML in a variable for further use.
Thanks.
MessageHandler:
Utilizing the extensible Handler framework provided by JAX-WS Specification and the better Message abstraction in RI, we introduced a new handler called MessageHandler to extend your Web Service applications. MessageHandler is similar to SOAPHandler, except that implementations of it gets access to MessageHandlerContext (an extension of MessageContext). Through MessageHandlerContext one can access the Message and process it using the Message API. As I put in the title of the blog, this handler lets you work on Message, which provides efficient ways to access/process the message not just a DOM based message. The programming model of the handlers is same and the Message handlers can be mixed with standard Logical and SOAP handlers. I have added a sample in JAX-WS RI 2.1.3 showing the use of MessageHandler to log messages and here is a snippet from the sample:
public class LoggingHandler implements MessageHandler<MessageHandlerContext> {
public boolean handleMessage(MessageHandlerContext mhc) {
Message m = mhc.getMessage().copy();
XMLStreamWriter writer = XMLStreamWriterFactory.create(System.out);
try {
m.writeTo(writer);
} catch (XMLStreamException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean handleFault(MessageHandlerContext mhc) {
.....
return true;
}
public void close(MessageContext messageContext) { }
public Set getHeaders() {
return null;
}
}
I get this warning
2017-05-25 00:48:43.125 WARN 7104 --- [nio-8080-exec-4] o.s.web.servlet.PageNotFound : Request method 'PUT' not supported
in intelliJ when I'm trying to do an update from c# (Visual Studio). But when I'm doing that update from Java, it works.
update method in Java:
#RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public Proba update(#RequestBody Proba proba) {
System.out.println("Updating proba ...");
try{
probaRepository.update(proba.getIdProba(),proba);
} catch (Exception e){
e.printStackTrace();
}
return proba;
}
C# method
static async Task<string> UpdateProbaAsync(string path, Proba proba)
{
string res = null;
HttpResponseMessage response = await client.PutAsJsonAsync(path, proba);
if (response.IsSuccessStatusCode)
{
res = await response.Content.ReadAsStringAsync();
}
return res;
}
and here is how I call UpdateProbaAsync
var rezU = await UpdateProbaAsync("http://localhost:8080/concurs/probe", new Proba(9, "cautare comori UPDATE", "3-5 ani", 0));
var probeUpdate = await GetProbaAsync("http://localhost:8080/concurs/probe");
foreach (var proba in probeUpdate)
{
Console.WriteLine(proba.ToString());
}
this is what I get for HttpResponseMessage response
+ response {StatusCode: 405, ReasonPhrase: '', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Connection: close
Date: Wed, 24 May 2017 21:57:39 GMT
Allow: POST
Allow: GET
Content-Type: application/json; charset=UTF-8
}} System.Net.Http.HttpResponseMessage
I guess you are missing the attribute from the c#
[HttpPut] //or [HttpPost]
[Route("/{path}")]
async Task<string> UpdateProbaAsync(string path, Proba proba)
{
}
default is GET and you are trying to put onto a GET API
The Java:
private void apiPasswordReset(final String msisdn) {
showLoading();
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(Constants.API_THREADPOOL_SIZE));
ListenableFuture<ResponseBase> response = service.submit(new Callable<ResponseBase>() {
#Override
public ResponseBase call() throws Exception {
return webService.passwordReset(
Constants.RESPONSE_TYPE_APPLICATION_JSON,
getResources().getString(R.string.api_key),
getResources().getString(R.string.channel_id),
getResources().getString(R.string.app_id),
getResources().getString(R.string.base_url),
getResources().getString(R.string.base_url_port),
getResources().getString(R.string.api_version_string),
msisdn
);
}
});
Futures.addCallback(response, new FutureCallback<ResponseBase>() {
#Override
public void onSuccess(final ResponseBase result) {
Log.i(TAG, "onSuccess()");
}
#Override
public void onFailure(Throwable t) {
Log.e(TAG, t.getMessage());
}
});
}
Response Model:
public class ResponseBase {
private boolean success;
private String response_code;
private String api_version;
private String message;
private String base_url;
}
The call:
#GET("/{endpoint}:{endpointPort}/api/{apiVersion}/users/{msisdn}/edit")
ResponseBase passwordReset(
#Header("Content-type") String contentType,
#Header("x-api-key") String apiKey,
#Header("channel-id") String channelId,
#Header("app-id") String appId,
#Path("endpoint") String endpoint,
#Path("endpointPort") String endpointPort,
#Path("apiVersion") String apiVersion,
#Path("msisdn") String msisdn
);
Request:
---> HTTP GET
x-api-key: 5ffc84c4-d1ad-29e8-4114-d84708bf96ac
channel-id: 1
app-id: android_001
Content-Type: application/json
---> END HTTP (no body)
Response:
<--- HTTP 200 (1013ms)
: HTTP/1.1 200 OK
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 217
Content-Type: application/json
Date: Mon, 11 Apr 2016 08:31:40 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.7 (Ubuntu)
Set-Cookie: XSRF-TOKEN=eyJpdiI6Ikt5RWM4UFhDc1hrVytNRkNlc0QySVE9PSIsInZhbHVlIjoiVmZ4KzF5bVdkY2xwbmJsaGZMbDZ1NldpNVp6bGsyemIyVGVKUzhcLzIrZDN3R3pGRWRVd0FWdnlnTjhaZCtyQ2JacTcybllvMW1ZOElaMU5TZUNpYUp3PT0iLCJtYWMiOiI3YjBiZDM4MjM4OWMxMDRlOThiODU5ZDc1M2RhZTA5YmYyNDM0ZGE1NDQ0ZjQ0YWRmOTM5MjQ1NTI0ODkwNTAxIn0%3D; expires=Mon, 11-Apr-2016 10:31:40 GMT; Max-Age=7200; path=/
Set-Cookie: laravel_session=eyJpdiI6ImsyVXcrRHpHY2FOakhZZDhIYjRnR1E9PSIsInZhbHVlIjoiQTRcL2g0c1Ztdk9MbTl3MlNTblwvdHhicStrTHMzYlZmb3I2ZVc1NjBwNWIwYWQ5NjB2UXVyQzZBSUpLTzRcL0dta0gxUVR2ZnhaWnFoQStEUm93Q0lESlE9PSIsIm1hYyI6ImQxYmY4NDk2OTgzNDZlZDVlMmM0MTUyMzMzN2ZhMmQ3YzY1ZWYyMTZlMDA4NWY3ZDc1ZTIzMTc1NzdmMzM3YjkifQ%3D%3D; expires=Mon, 11-Apr-2016 10:31:40 GMT; Max-Age=7200; path=/; httponly
X-Android-Received-Millis: 1460363500117
X-Android-Response-Source: NETWORK 200
X-Android-Sent-Millis: 1460363499337
X-Powered-By: PHP/5.5.9-1ubuntu4.14
Version OK 5.5.9-1ubuntu4.14
{"success":true,"response_code":"OK","api_version":1,"message":"PASSWORD RESET NOTIFICATION SENT SUCCESSFULLY","error":[],"base_url":"http:\/\/apiserver.com","data":[]}
The response data seems to fit the model. When I run this call with postman it returns valid json aswell. I have commented out all fields in the model and still get the same error.
Any help would be appreciated :)
Versions:
Android studio 2.0
Gradle 2.0
Retrofit 1.9.0
Guava 19.0
FIX:
Due to my own stupidity :|
Server was including text ouside the object in the response that should be part of the header. Thanks for the assist guys!
Postman response:
Version OK 5.5.9-1ubuntu4.14
{"success":true,"response_code":"OK","api_version":1,"message":"PASSWORD RESET NOTIFICATION SENT SUCCESSFULLY","error":[],"base_url":"http:\/\/apiserver.com","data":[]}
i have this http header :
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Tue, 15 Mar 2016 17:08:29 GMT
And what i want is to add 2 parameter: mytotalcount and mytotalresult.
i have to add this into my response however it's not working i can't do:
response.Headers.Add("mytotalcount", "10");
Also can't do
request.setAttribute("mytotalcount","10");
So i am blocked any ideas please ? Thanks for your help !
Here is the part of the code:
public class SitesResponse {
private Result result;
private List<GeographicSite> site;
public SitesResponse () {
this.result = new Result();
this.site = new ArrayList<GeographicSite>();
}
public List<GeographicSite> getSite() {
return site;
}
public void setSite(List<GeographicSite> site) {
this.site = site;
}
}
Ensuite l'autre classe qui utilise SitesResponse
SitesResponse response = new SitesResponse();
et
if (testiing) {
try {response = siteManager.geographicSitesAPIV1(args);
response.getResult().setCode("error");
response.getResult().setLabel("no addr found");
And this is what i tried ... earlier
System.out.println(response.toString().getBytes().toString()+"azezae");
// request.Headers.Add("headername", "headervalue");
// request.setAttribute("X-Total-Count","10");
//response.setAttribute("X-Result-Count", "7");
//response.setIntHeader("mytotalcount", 5);
//////////////////////////////////////////////////:::::::
In picture where i want to add my two parameters result from SOAPui
Hello again Thank you for your time,
i was trying to edited the wrong class so what i did you just
resp.addIntHeader(att, 10);
resp.addIntHeader(att2, 5);
Thank you for your time and answers!
I generate proxy classes with wsdl.exe to request web-services, that are probably build at java platform. The problem is with encoding of response. I get '?' instead of russian letters.(for example '????26' instead of 'АН26')
I also use soapUI and everything works well there. I am not experienced at configuring .Net clients. So how I could determine and configure proper encoding for response. I already played with app.config as next:
I attach headers information here. I don't wee encoding info at responce headers...
request headers:
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "urn:#DCSSci_ListFlight_5"
Content-Length: 641
Host: 109.73.1.66:23022
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
response headers:
HTTP/1.1 200 OK
Date: Thu, 06 Sep 2012 03:47:52 GMT
Server: Apache/2.2.10 (Linux/SUSE)
200 OKX-FidelXML-Version: 2.0
Content-length: 15464
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/xml
Solution:
public class TraceExtension : SoapExtension
{
Stream oldStream;
Stream newStream;
public override Stream ChainStream(Stream stream)
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override object GetInitializer(Type WebServiceType)
{
return null;
}
public override void Initialize(object initializer)
{
}
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
newStream.Position = 0;
Copy(newStream, oldStream);
break;
case SoapMessageStage.BeforeDeserialize:
message.ContentType = "application/soap+xml; utf-8";
Copy(oldStream, newStream);
newStream.Position = 0;
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
void Copy(Stream from, Stream to)
{
TextReader reader = new StreamReader(from, System.Text.Encoding.GetEncoding("utf-8"));
TextWriter writer = new StreamWriter(to, System.Text.Encoding.GetEncoding("utf-8"));
writer.WriteLine(reader.ReadToEnd());
writer.Flush();
}
}
[AttributeUsage(AttributeTargets.Method)]
public class TraceExtensionAttribute : SoapExtensionAttribute
{
private int priority;
public override Type ExtensionType
{
get { return typeof(TraceExtension); }
}
public override int Priority
{
get { return priority; }
set { priority = value; }
}
}
And than just add
[TraceExtension()]
attribute for proxy invoke method
You can override GetWebResponse of your proxy and change the encoding
public class YourProxyClass : SoapHttpClientProtocol
{
protected override WebResponse GetWebResponse(WebRequest request)
{
var response = base.GetWebResponse(request);
response.Headers["Content-Type"] = "text/xml; charset=utf-8"; //<==
return response;
}
}