Client Response Application.Json - java

I´m trying to create a client for some Rest application. I tested the Rest application with Advanced REST client in Chrome.
I received:
{
"authorization": false,
"provider": "Provider"
}
That is okey.
but I would like obtain this in my client:
public class MainApp extends Application {
public static final String BASE_URI = "http://localhost:8000/test";
public static final String PATH_NAME= "/sytem/Consumer/r/Provider";
#Override
public void start(Stage stage) throws Exception {
}
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(BASE_URI).path(PATH_NAME);
Response response = target.request(MediaType.APPLICATION_JSON).get();
System.out.println(response);
client.close();
}
}
I only receive this in the terminal:
λ java -jar Client_consumer-1.0-SNAPSHOT.jar
org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine$1#6591f517
The class is :
#XmlRootElement
public class Auth_response implements Serializable {
private String Provider;
private boolean authorization;
public Auth_response() {
super();
}
public Auth_response(String Provider, boolean authorization) {
super();
this.Provider = Provider;
this.authorization = authorization;
}
public String getProvider() {
return Provider;
}
public boolean isAuthorization() {
return authorization;
}
public void setProvider(String Provider) {
this.Provider = Provider;
}
public void setAuthorization(boolean authorization) {
this.authorization = authorization;
}
#Override
public String toString() {
return "Auth_response{" + "Provider=" + Provider + ", authorization=" + authorization + '}';
}
}
I would like to know how to print properly the response, and how to convert to a java object again. I tried with some examples, but nothing works and I think that I need some guide.
EDIT:
I tried this for getting the object:
Auth_response r=
client.target("http://localhost:8000/test/system/Consumer/r/Provider")
.request(MediaType.APPLICATION_JSON_TYPE).
get(Auth_response.class);
System.out.println("funciona:");
System.out.println(r.getProvider());
System.out.println(r.isAuthorization());
But I obtain the next error:
Caused by: javax.ws.rs.ProcessingException: RESTEASY003145: Unable to find a MessageBodyReader of content-type application/json and type class ah.client_consumer.Auth_response
at org.jboss.resteasy.core.interception.ClientReaderInterceptorContext.throwReaderNotFound(ClientReaderInterceptorContext.java:42)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.getReader(AbstractReaderInterceptorContext.java:75)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:52)
at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.aroundReadFrom(GZIPDecodingInterceptor.java:59)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:55)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readFrom(ClientResponse.java:251)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readEntity(ClientResponse.java:181)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:213)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.extractResult(ClientInvocation.java:105)
... 14 more
Exception running application ah.client_consumer.MainApp

Try changing below line :
Response response = target.request(MediaType.APPLICATION_JSON).get();
System.out.println(response);
To
Response response = target.request(MediaType.APPLICATION_JSON).get(String.class);
System.out.println(response.toString());
Because you have not specified what type of response you are accepting, you are getting object as response.

SOLUTION:
Add to the code:
ResteasyProviderFactory instance=ResteasyProviderFactory.getInstance();
RegisterBuiltin.register(instance);
instance.registerProvider(ResteasyJacksonProvider.class);
The solution was finding in : Unable to find a MessageBodyReader of content-type application/json and type class java.lang.String

Related

Java Glassfish 4.1.2 Error 500 when trying to consume JSON

I am just starting with Glassfish, and trying to set up a restful web service that can take a JSON string and parse it and return proper results. The web service looks like this:
#Path("/process")
public class SurveyResponseProcessor
{
#GET
#Produces("text/plain")
public String getReferrals()
{
return "Only POST operation are supported.";
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String postReferrals(ResponseDetails details)
{
return "done - " + details.getSurveyId();
}
}
The class that I expected to get the JSON:
#XmlRootElement
public class ResponseDetails
{
#XmlElement String providerId;
#XmlElement String surveyId;
#XmlElement String respondentId;
public String getProviderId()
{
return providerId;
}
public void setProviderId(String providerId)
{
this.providerId = providerId;
}
public String getSurveyId()
{
return surveyId;
}
public void setSurveyId(String surveyId)
{
this.surveyId = surveyId;
}
public String getRespondentId()
{
return respondentId;
}
public void setRespondentId(String respondentId)
{
this.respondentId = respondentId;
}
}
The POST body: {"providerId":"1","surveyId":"5","respondentId":"23"}
The error message:
<p><b>message</b>Internal Server Error</p><p><b>description</b>The server encountered an internal error that prevented it from fulfilling this request.</p>
Nothing shows up in any of the logs.
EDIT TO ADD: If I set it to consume text and change the arguments, this works just fine, telling me it is not a routing issue. Is it possible I haven't set JAXB or Jersey somewhere? I am using IntelliJ, if that matters.

How to convert cURL to retrofit correct form?

Sorry for my English. I want use this service. For determine the language of the text.
Request(Curl):
curl -X POST -d "outputMode=json" --data-urlencode text#ibm.txt -d "url=http://www.ibm.com/us-en/" "https://gateway-a.watsonplatform.net/calls/text/TextGetLanguage?apikey=%API_KEY%"
I use Retrofit for request.
public interface LanguageDetectionApi {
public static final String ROOT_URL = "https://gateway-a.watsonplatform.net/calls/";
#POST("/text/TextGetLanguage")
Call<List<PostModel>> getData(#Query("apikey") String apikey, #Query("text") String text);
}
Create retrofit object:
public class App extends Application {
private static LanguageDetectionApi _languageDetectionApi;
private Retrofit _retrofit;
#Override
public void onCreate() {
super.onCreate();
_retrofit = new Retrofit.Builder()
.baseUrl(_languageDetectionApi.ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
_languageDetectionApi = _retrofit.create(LanguageDetectionApi.class);
}
public static LanguageDetectionApi getLanguageDetectionApi() {
return _languageDetectionApi;
}
}
And send request:
App app = new App();
app.onCreate();
app.getLanguageDetectionApi().getData("4978e60252ae102dfe1341146bb8cc3ec4bbbd78", textForRecognition).enqueue(new Callback<List<PostModel>>() {
#Override
public void onResponse(Call<List<PostModel>> call, Response<List<PostModel>> response) {
List<PostModel> posts = new ArrayList<>();
posts.addAll(response.body());
}
#Override
public void onFailure(Call<List<PostModel>> call, Throwable t) {
Toast.makeText(MainActivity.this, "An error occurred during networking", Toast.LENGTH_SHORT).show();
}
});
PostModel i generated in site http://www.jsonschema2pojo.org/.
Questions:
No response comes to me, although apikey are exactly valid.
How to specify in the interface parametr "outputMode=json"?
And I translated correctly cURL to LanguageDetectionApi?
It seems to me that the whole mistake in the class LanguageDetectionApi. Can you help deal with this? Thank you!
change url code like below:
public interface LanguageDetectionApi {
public static final String ROOT_URL = "https://gateway-a.watsonplatform.net";
#POST("/calls/text/TextGetLanguage")
Call<List<PostModel>> getData(#Query("apikey") String apikey, #Query("text") String text);
}
base url should be ony host name.

Java client for REST web service with Netbeans

I am trying to write a Java client for a REST web service, defined this way:
#Path("/")
public class Translator {
public Translator() { }
#POST
#Produces("application/json")
#Path("/translate")
public String translate(#QueryParam("dir") String dir, #QueryParam("string")String string, #QueryParam("user")String user, #QueryParam("key")String key){
return doTranslation(dir, string, user, key);
}
}
I have tried to use the NetBeans option "New Restful Java client", selecting for the REST source the project that contains the webservice.
But it generates a class with one method that does not have parameters:
public class NewJerseyClient {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8086/TranslatorREST/Translator";
public NewJerseyClient() {
client = javax.ws.rs.client.ClientBuilder.newClient();
webTarget = client.target(BASE_URI);
}
public String translate() throws ClientErrorException {
return webTarget.path("translate").request().post(null, String.class);
}
}
So I don't see a way to pass parameters to the web service.
I can succesfully use this web service from SoapUI, provided that I don't enable the option "Post QueryString", in which case the web service receives "null" for all the parameters.
Thanks in advance.
You can add the parameters with .queryParam() :
public class NewJerseyClient {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8086/TranslatorREST/Translator";
public NewJerseyClient() {
client = javax.ws.rs.client.ClientBuilder.newClient();
webTarget = client.target(BASE_URI);
}
public String translate() throws ClientErrorException {
return webTarget.path("translate").queryParam("dir", "myDir")
.queryParam("string", "myString")
.queryParam("user", "myUser")
.queryParam("key", "myKey").request().post(null, String.class);
}
}

org.jboss.resteasy.client.ClientResponseFailure: Unable to find a MessageBodyReader of content-type text/plain and type class java.lang.String

org.jboss.resteasy.client.ClientResponseFailure: Unable to find a MessageBodyReader of content-type text/plain and type class java.lang.String
Please help to solve the issue
Provider App :
#Path("/payment")
public class PaymetResource {
Object object=null;
#Path("{type}/{gateWay}")
public Object getResource(#PathParam("type") String type){
if(type.equals("creditCard"))
object = new CreditCardPaymentResource();
if(type.equals("debitCard"))
object = new DebitCardPaymentResource();
return object;
}
}
public class CreditCardPaymentResource {
/*
#GET
#Produces(MediaType.TEXT_PLAIN)
public String processPayments(){
return "hi boss";
}*/
#GET
#Produces(MediaType.TEXT_PLAIN)
public Response processPayment(#QueryParam("cardNo") String cardNo,#PathParam("gateWay") String gateWay){
String result="processed payment with Gateway:"+gateWay+" and cardNo :"+cardNo;
return Response.status(201).entity(result).build();
//return "processed payment with Gateway:"+gateWay+" and cardNo :"+cardNo;
}
}
public class DebitCardPaymentResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String processPayment(#QueryParam("cardNo") String cardNo,#PathParam("gateWay") String gateWay,#QueryParam("pin") String pin){
return "processed payment with Gateway:"+gateWay+" and cardNo :"+cardNo+"pin No"+pin;
}
}
client app :
public class RestFirstClient{
public static void main(String[] args) {
try{
ClientRequest request = new ClientRequest("http://localhost:8081/DynamicDispatch/rest/payment/creditCard/HDFC");
request.accept("text/plain");
request.queryParameter("cardNo", "669888554");
ClientResponse<String> response = request.get(String.class);
System.out.println(response.getEntity().toString());
}catch (Exception e) {
e.printStackTrace();
}
}
}
My program is working fine when we access the service through the url. Please help me
Url :http://localhost:8081/DynamicDispatch/rest/payment/creditCard/HDFC?cardNo=99809990876
output :processed payment with Gateway:HDFC and cardNo :99809990876
The combination of content-type text/plain and type class java.lang.String is handled by the org.jboss.resteasy.plugins.providers.StringTextStar found in resteasy-core.
And the client is created like:
final ResteasyClient client =
new ResteasyClientBuilderImpl() //
.connectTimeout(10, SECONDS) //
.readTimeout(10, SECONDS) //
.connectionCheckoutTimeout(10, SECONDS) //
.register(new StringTextStar()) //
.build();
final ResteasyWebTarget target = client.target(UriBuilder.fromPath("whatever path"));
final CreditCardPaymentResource client = target.proxy(CreditCardPaymentResource.class);

How to get the response header in a RestEasy client?

i´m implementing a Restful service using Jax-RS 2.0 (Resteasy 3.0.7.Final) and share the interface between client and service.
The return value is void because ClientResponse is deprecated since RestEasy introduced JAX-RS 2.0 in version 3+.
To return the location of the new created object i inject the response, using the #Context annotation, and add the Content-Location header.
For example:
Shared Interface:
#Path("/")
#Consumes("application/xml")
#Produces("application/xml")
interface Resource {
#Path("createSomething")
void createSomething(AnyObject object);
...
}
Implementation class (The Service):
class ResourceImpl {
...
#Context org.jboss.resteasy.spi.HttpResponse response;
...
#Override
void createSomething(AnyObject object) throws AnyException {
String id = service.create(object);
response.getOutputHeaders().putSingle("Content-Location",
"/createSomething/" + id);
response.setStatus(Response.Status.CREATED.getStatusCode());
}
}
The client (build with the Resteasy Proxy Framework):
...
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(baseUrl);
Resource resource = (Resource) target.proxy(Resource.class);
resource.createSomething(anyObject);
...
How can i retrieve Header information (and others, like Atom Links) which has been injected by the service?
Is it reasonable to use client side Filters and Interceptors?
Thank You
The best solution i found was to use a Filter to process the incoming response header.
public class HeaderFilter implements ClientResponseFilter {
private Map<String, String> headers = new HashMap<>();
private List<String> headerFilter = new ArrayList<>();
public final void addHeaderFilter(final String header) {
headerFilter.add(header);
}
public final void removeHeaderFilter(final String header) {
headerFilter.remove(header);
}
public final String getHeader(final String header) {
return headers.get(header);
}
#Override
public final void filter(final ClientRequestContext requestContext,
final ClientResponseContext responseContext)
throws IOException {
headers = new HashMap<>();
for (String headerToLookFor : headerFilter) {
String header = responseContext.getHeaderString(headerToLookFor);
if (header != null) {
headers.put(headerToLookFor, header);
} else {
...
}
}
}
}

Categories