Как отправлять и получать данные JSON из спокойного веб-сервиса с использованием API Джерси
@Path("/hello")
public class Hello {
@POST
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JSONObject sayPlainTextHello(@PathParam("id")JSONObject inputJsonObj) {
String input = (String) inputJsonObj.get("input");
String output="The input you sent is :"+input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
Это мой webservice (я использую API Джерси). Но я не мог понять способ вызова этого метода из клиента java rest для отправки и получения json-данных. Я попробовал следующий способ написать клиент
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("input", "Value");
System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).entity(inputJsonObj).post(JSONObject.class,JSONObject.class));
Но это показывает следующую ошибку:
Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class java.lang.Class, and MIME media type, application/octet-stream, was not found
Ответы
Ответ 1
Ваше использование @PathParam неверно. Он не соответствует этим требованиям, как описано в javadoc здесь. Я считаю, что вы просто хотите ПОЧТИ сущность JSON. Вы можете исправить это в своем ресурсном методе, чтобы принять объект JSON.
@Path("/hello")
public class Hello {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {
String input = (String) inputJsonObj.get("input");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
И ваш код клиента должен выглядеть следующим образом:
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new LoggingFilter());
WebResource service = client.resource(getBaseURI());
JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("input", "Value");
System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));
Ответ 2
Для меня параметр (JSONObject inputJsonObj) не работал. Я использую Джерси 2. * Следовательно, я чувствую, что это
java (Jax-rs) и Angular way
. Надеюсь, это будет полезно для тех, кто использует JAVA Rest и AngularJS, как я.
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> methodName(String data) throws Exception {
JSONObject recoData = new JSONObject(data);
//Do whatever with json object
}
На стороне клиента я использовал AngularJS
factory.update = function () {
data = {user:'Shreedhar Bhat',address:[{houseNo:105},{city:'Bengaluru'}]};
data= JSON.stringify(data);//Convert object to string
var d = $q.defer();
$http({
method: 'POST',
url: 'REST/webApp/update',
headers: {'Content-Type': 'text/plain'},
data:data
})
.success(function (response) {
d.resolve(response);
})
.error(function (response) {
d.reject(response);
});
return d.promise;
};
Ответ 3
Вышеупомянутая проблема может быть решена путем добавления следующих зависимостей в ваш проект, поскольку я столкнулся с той же проблемой. Для более подробного ответа на это решение, пожалуйста, обратитесь по ссылке SEVERE: MessageBodyWriter не найден для типа носителя = application/xml type = класс java.util.HashMap
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>