how to create client TGT with java cxf - java

I'm new to the java rest CXF client. I will make various requests to a remote server, but first I need to create a Ticket Granting Ticket (TGT). I looked through various sources but I could not find a solution. The server requests that I will create a TGT are as follows:
Content-Type: text as parameter, application / x-www-form-urlencoded as value
username
password
I create TGT when I make this request with the example URL like below using Postman. (URL is example). But in the code below, I'm sending the request, but the response is null. Could you help me with the solution?
The example URL that I make a request with POST method using Postman: https://test.service.com/v1/tickets?format=text&username=user&password=pass
List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJsonProvider());
WebClient client = WebClient.create("https://test.service.com/v1/tickets?format=text&username=user&password=pass", providers);
Response response = client.getResponse();

You need to do a POST, yet you did not specify what your payload looks like?
Your RequestDTO and ResponseDTO have to have getters/setters.
An example of using JAX-RS 2.0 Client.
Client client = ClientBuilder.newBuilder().register(new JacksonJsonProvider()).build();
WebTarget target = client.target("https://test.service.com/v1/tickets");
target.queryParam("format", "text");
target.queryParam("username", "username");
target.queryParam("password", "password");
Response response = target.request().accept(MediaType.APPLICATION_FORM_URLENCODED).post(Entity.entity(yourPostDTO,
MediaType.APPLICATION_JSON));
YourResponseDTO responseDTO = response.readEntity(YourResponseDTO.class);
int status = response.getStatus();
Also something else that can help is if you copy the POST request from POSTMAN as cURL request. It might help to see the differences between your request and POSTMAN. Perhaps extra/different headers are added by postman?
Documentation: https://cxf.apache.org/docs/jax-rs-client-api.html#JAX-RSClientAPI-JAX-RS2.0andCXFspecificAPI
Similar Stackoverflow: Is there a way to configure the ClientBuilder POST request that would enable it to receive both a return code AND a JSON object?

Related

how to insert body in a post request with akka library using java

have to use akka library with java and i need to do a post request with body in it, a body like this: {"subjectId":961,"other":null}
In this application, I have some examples already written with get requests and parameters to those requestes. but now i need to send a post request with body in it.
The following snippet is correct? if not, can you tell me what i do wrong? thanks.
..
Http http = new Http((ExtendedActorSystem) context().system());
HttpRequest postRequest = HttpRequest.POST(url)
.withEntity(MediaTypes.APPLICATION_JSON.toContentType(),
"{\"subjectId\": 961, \"other\": null,}");
CompletionStage<HttpResponse> response = http.singleRequest(postRequest);
..

How to send body as a Json in RestTemplate to get data from API [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
HTTP GET with request body
I've read few discussions here which do not advocate sending content via HTTP GET. There are restrictions on the size of data that can be sent via clients (web browsers). And handling GET data also depends on servers. Please refer section Resources below.
However, I've been asked to test the possibility to send content via HTTP GET using RestTemplate. I refered few discussions on spring forum but they were not answered. (Please note sending data via http Post works fine). The discussion here suggests using POST instead.
dev env - JBoss AS 5.1, Spring 3.1.3
Client
#Test
public void testGetWithBody()
{
// acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.TEXT_PLAIN);
// header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
// body
String body = "hello world";
HttpEntity<String> entity = new HttpEntity<String>(body, headers);
Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("id", "testFile");
// Send the request as GET
ResponseEntity<String> result = restTemplate.exchange(
"http://localhost:8080/WebApp/test/{id}/body",
HttpMethod.GET, entity, String.class, uriVariables);
Assert.assertNotNull(result.getBody());
}
Server #Controller
#RequestMapping(value = "/{id}/body", method = RequestMethod.GET)
public #ResponseBody
String testGetWithBody(#PathVariable String id,
#RequestBody String bodyContent)
{
return id + bodyContent;
}
The problem -
executing this test case returns 500 Internal Server Error. On debugging, I found that the controller is not hit.
Is it correct to understand that the RestTemplate provides the way to send data as request body, but the error occurs because the server could not handle the request body ?
If the request body sent via HTTP Get is not conventional why does RestTemplate provide the APIs to allow sending it ? Does this mean there are few servers capable of handling the Request body via GET ?
Resources - discussions on sending body via HTTP GET using RestTemplate at spring forum
http://forum.springsource.org/showthread.php?129510-Message-body-with-HTTP-GET&highlight=resttemplate+http+get
http://forum.springsource.org/showthread.php?94201-GET-method-on-RestTemplate-exchange-with-a-Body&highlight=resttemplate+http+get
Resources - General discussions on sending body via HTTP GET
get-with-request-body
is-this-statement-correct-http-get-method-always-has-no-message-body
get-or-post-when-reading-request-body
http-uri-get-limit
Is it correct to understand that the RestTemplate provides the way to send data as request body, but the error occurs because the server could not handle the request body ?
You can tell by looking at network traffic (does the request get sent with a request body and a GET method?) and at server logs (the 500 result you receive must have a server-side effect that gets logged, and if not, configure the server to do so).
If the request body sent via HTTP Get is not conventional why does RestTemplate provide the APIs to allow sending it ? Does this mean there are few servers capable of handling the Request body via GET ?
Because it is a generic class that also allows you to craft requests that can include a message body.
As stated in HTTP GET with request body:
In other words, any HTTP request message is allowed to contain a message body, and thus [a server] must parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request. The requirements on parsing are separate from the requirements on method semantics.
A body on a GET cannot do anything semantically, because you are requesting a resource. It's like you tell the server: "Give me resource X, oh, and have some apples!". The server won't care about your apples and happily serve resource X - or throw an error because it doesn't like any offers in a request.
However, I've been asked to test the possibility to send content via HTTP GET
Please tell the one who requested this that this is a case that should not have to be tested, because no sensible implementation supports it.

Elasticsearch Java client: can't connect to the remote server

I need to connect to the remotely located ElasticSearch index, using the url provided here:
http://api.exiletools.com/info/indexer.html
However, I can't figure out how to do this in Java.
Docs on ES Java Client don't really have much info at all.
I also did not find any JavaDocs for it, do they exist?
Now, there are working examples written in Python, which confirm that the server is up and running, connection part looks like this:
es = Elasticsearch([{
'host':'api.exiletools.com',
'port':80,
'http_auth':'apikey:DEVELOPMENT-Indexer'
}])
What I tried to do:
client = new TransportClient()
.addTransportAddress(new InetSocketTransportAddress("apikey:DEVELOPMENT-Indexer#api.exiletools.com/index", 9300));
also tried ports 9200 and 80
This results in:
java.nio.channels.UnresolvedAddressException
and NoNodeAvailableException
The Shop Indexer API offers an HTTP entry point on port 80 to communicate with their ES cluster via the HTTP protocol. The ES TransportClient is not the correct client to use for that as it will only communicate via TCP.
Since Elasticsearch doesn't provide an HTTP client out of the box, you need to either use a specific library for that (like e.g. Jest) or you can roll up your own REST client.
An easy way to achieve the latter would be using Spring's RestTemplate:
// create the REST template
RestTemplate rest = new RestTemplate()
// add the authorization header
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "DEVELOPMENT-Indexer");
// define URL and query
String url = "http://api.exiletools.com/index/_search";
String allQuery = "{\"query\":{\"matchAll\":{}}}";
// make the request
HttpEntity<String> httpReq = new HttpEntity<String>(allQuery, headers);
ResponseEntity<String> resp = rest.exchange(url, HttpMethod.POST, httpReq, String.class)
// retrieve the JSON response
String body = resp.getBody();

how to check what exacly request i send to restful webservice via restful client (javax.ws.rs.client)

I`m looking answer to question how it is possible to check what exacly request body and headers i send to restful webservice using restful client. For example and following code bellow:
// client object
Client client = javax.ws.rs.client.ClientBuilder.newClient();
// Web target
WebTarget webTarget = client.target(BASE_URI)
// Sending a request
webTarget
.request(MediaType.APPLICATION_XML)
.cookie(cookie)
.post(Entity.entity(params,MediaType.APPLICATION_XML));
how to debug, monitor or overview this request? It is possible?
Might be easiest to use something like Postman extension for Chrome: https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
This will allow you to set all relevant headers and the request body and easily debug API calls.

How to send a POST request with parameters to an endpoint via JBoss HttpRouter?

I'm working on an ESB project and I need to call a REST service using a POST request. HttpRouter seems to be the right way to do it since it supports both GET and POST methods but I can't find a way to inject parameters inside my call.
How can I do that ?
You can try Apache HTTP library. It's very easy to use and have comprehensive set of class needed to manipulate HTTP request.
Found the answer... It was pretty dumb. All you need to do is to inject parameters inside the Message object and they will be in the body of the request. Here is a sample code created by JBoss and found from a unit test of HttpRouter :
final ConfigTree tree = new ConfigTree("WrappedMessage");
tree.setAttribute("endpointUrl", "http://127.0.0.1:8080/esb-echo");
tree.setAttribute("method", "post");
tree.setAttribute("unwrap", "false");
tree.setAttribute("MappedHeaderList", "SOAPAction, Content-Type, Accept, If-Modified-Since");
HttpRouter router = new HttpRouter(tree);
Message message = MessageFactory.getInstance().getMessage(type);
message.getBody().add("bar");
Message response = router.process(message);
String responseBody = (String)response.getBody().get();
String responseStr = null;
if (deserialize)
responseStr = Encoding.decodeToObject(responseBody).toString();
else
responseStr = responseBody;
return responseStr;

Categories