jersey-gson Content-Type Woes

Another update to my jersey-gson project today. I was trying to add some jersey-client unit tests to the project, but I just couldn’t get the GsonReader and GsonWriter classes to work on the client. The tests worked with manually generated JSON, but failed with automatically generated JSON.

I tried adding a LoggingFilter to examine the actual request being sent to the server, but nothing jumped out at me. Then I added Mono Fiddler as a debugging proxy server and I saw it.

The request succeeded with “Content-Type: application/json”
The request failed with “Content-Type: application/json; charset=UTF-8”

A quick change to GsonWriter and my client requests started working.

1
2
3
4
5
6
7
8
9
10
11
diff --git a/src/main/java/com/ideoplex/tutorial/GsonWriter.java b/src/main/java/com/ideoplex/tutorial/GsonWriter.java
index 9ef181d..95a12c3 100644
--- a/src/main/java/com/ideoplex/tutorial/GsonWriter.java
+++ b/src/main/java/com/ideoplex/tutorial/GsonWriter.java
@@ -42,7 +42,6 @@ public class GsonWriter<T> implements MessageBodyWriter<T> {
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream)
throws IOException, WebApplicationException {
- httpHeaders.get("Content-Type").add("charset=UTF-8");
entityStream.write(gson.toJson(t).getBytes("UTF-8"));
}

Of course, code changes always cascade. Now my selenium browser tests were failing. A little exploration in the browser developer tools revealed that JSON.parse was the culprit. Another code update and the tests were succeeding.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
diff --git a/src/main/webapp/index.html b/src/main/webapp/index.html
index 9568c94..f147ace 100644
--- a/src/main/webapp/index.html
+++ b/src/main/webapp/index.html
@@ -134,13 +134,13 @@
type: "POST",
url: "webapi/myresource/user/post",
data: JSON.stringify(json),
- contentType: "application/json; charset=utf-8",
+ contentType: "application/json",
error: function(xhr,status,error) {
bootbox.alert(xhr.responseText);
},
success: function(data,status,xhr){
form[0].reset();
- $('#users').DataTable().row.add(JSON.parse(data)).draw(false);
+ $('#users').DataTable().row.add(data).draw(false);
}
});
}
@@ -151,14 +151,14 @@
type: "POST",
url: "webapi/myresource/user/edit",
data: JSON.stringify(json),
- contentType: "application/json; charset=utf-8",
+ contentType: "application/json",
error: function(xhr,status,error) {
bootbox.alert(xhr.responseText);
$('#users tbody tr.selected').removeClass('selected');
},
success: function(data,status,xhr){
form[0].reset();
- $('#users').DataTable().row('.selected').data(JSON.parse(data)).draw(false);
+ $('#users').DataTable().row('.selected').data(data).draw(false);
$('#users tbody tr.selected').removeClass('selected');
}
});

25 Oct Autostart Jetty in Maven
01 Nov Jersey Client with Gson