I have been playing around and creating multiple small Java RESTful client libraries for different services at my company. Most of the time, I am unable to change anything on the server side and I need to write the Jersey pieces of code to interact with existing RESTful APIs.
Context
Up to know, I have been using Jersey with Jackson to use JSON: when I query a POJO I deserialize it from JSON, and when I need to send a POJO, I serialize it into a JSON body. This two kinds of snippets have been doing the job for me up to now...
Querying and de-serialization
ClientResponse response = webResource
.path("/path/to/resource")
.queryParam("key", "value")
.accept(Mediatype.APPLICATION_JSON)
.get(ClientResponse.class);
// (...) Check response status code
MyClassPojo pojo = response.getEntity(MyClassPojo.class);
Serialization and sending
ClientResponse response = webResource
.path("/path/to/resource")
.type(Mediatype.APPLICATION_JSON_TYPE)
.accept(Mediatype.APPLICATION_JSON)
.post(ClientResponse.class, pojo)
// (...) Check response status code
Issue
I am now facing a RESTful server that does not accept JSON bodies for sending my POJOs. The only thing that seem to work is to use query parameters.
For instance, if I want to send the object
public MyClassPojo {
public int attr1;
public String attr2;
}
MyClassPojo pojo = new MyClassPojo();
pojo.attr1 = 42;
pojo.attr2 = "Foo bar";
I would have loved to serialize it in JSON:
{
"attr1": 42,
"attr2": "Foo bar"
}
But this specific RESTful server is expecting query params:
?attr1=42&attr2=Foo+bar
Question
This kinda sucks, but I don't really have a choice... and I am now hoping that there is an easy way to achieve this with Jersey: how can I automatically serialize objects as query parameters, to send to a RESTful server?
Note: I closed this question as @Jukka answered it. Don't hesitate referring to a new question you create, if like me you are actually looking for a way to send x-www-form-urlencoded data. I am about to get something working...
Update
Following an idea from @Jukka I wrote the following method:
public MultivaluedMap<String, String> toQueryParams() {
final MultivaluedMap<String, String> queryParams = new Form();
final Field[] fields = getClass().getDeclaredFields();
for (Field field : fields) {
final boolean accessible = field.isAccessible();
try {
field.setAccessible(true);
final Object value = field.get(this);
if (value != null) {
final String name = field.getName();
queryParams.add(name, value.toString());
}
} catch (IllegalAccessException e) {
LOGGER.error("Error accessing a field", e);
} finally {
field.setAccessible(accessible);
}
}
return queryParams;
}
This is a great starting point, and would work perfectly if you actually do need Query Params. In my case, I got confused and I actually need a x-www-form-urlencoded! For that purpose I had to write a MessageBodyWriter!
My form encoding provider
@Produces(MediaType.APPLICATION_FORM_URLENCODED)
public class MyFormEncodingProvider implements MessageBodyWriter<Object> {
private static final String ENCODING = "UTF-8";
@Override
public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return true;
}
@Override
public long getSize(Object obj, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(Object obj, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> stringObjectMultivaluedMap, OutputStream outputStream) throws IOException, WebApplicationException {
final Writer osWriter = new OutputStreamWriter(outputStream);
final MultivaluedMap<String, String> fieldsAndValues = getFieldsAndValues(obj);
boolean firstVal = true;
for (Entry<String, List<String>> entry : fieldsAndValues.entrySet()) {
final List<String> values = entry.getValue();
if (values == null || values.size() == 0) {
if (!firstVal) {
osWriter.write("&");
}
osWriter.write(entry.getKey() + "=");
firstVal = false;
} else {
for (String value : values) {
if (!firstVal) {
osWriter.write("&");
}
osWriter.write(entry.getKey() + "=" + URLEncoder.encode(value, ENCODING));
firstVal = false;
}
}
}
osWriter.flush();
osWriter.close();
}
private static MultivaluedMap<String, String> getFieldsAndValues(Object obj) {
// Find all available fields
final Collection<Field> allFields = new ArrayList<>();
Class<?> clazz = obj.getClass();
while (clazz != null && clazz != Object.class) {
Collections.addAll(allFields, clazz.getDeclaredFields());
clazz = clazz.getSuperclass();
}
// Get all non-null values
final MultivaluedMap<String, String> queryParams = new Form();
for (Field field : allFields) {
final boolean accessible = field.isAccessible();
try {
field.setAccessible(true);
final Object value = field.get(obj);
if (value != null) {
final String name = field.getName();
queryParams.add(name, value.toString());
}
} catch (IllegalAccessException e) {
Logger.getLogger(AbstractIMSPojo.class).error("Error accessing a field", e);
} finally {
field.setAccessible(accessible);
}
}
return queryParams;
}
}
I would just implement this kind of view to your POJO:
class Pojo {
...
public MultiValuedMap<String,String> asQueryParams() {
...
}
}
and pass the result to WebResource.queryParams(..)
.
来源:https://stackoverflow.com/questions/17067927/how-to-serialize-a-pojo-into-query-params-with-jersey