vendredi 27 février 2015

java: Spring @RequestBody and @ResponseBody not working with java.net

Here is my java.net client code



URL server = new URL(serverUrl);
URLConnection connection = server.openConnection();

/* DoOutput flag is set to true to inform URL connection that we are
* sending data out. The default behavior is false. This will change
* the request from GET to a POST.
*/
connection.setDoOutput (true);

/* Setting the UseCaches to false allows the application "tunnel
* through" and ignore the caches.
*/
connection.setUseCaches (false);

connection.setRequestProperty ( "Content-Type", "application/octet-stream" );

ObjectOutputStream sendData = new ObjectOutputStream(connection.getOutputStream());
sendData.writeObject(packet);
sendData.flush();
sendData.close();

ObjectInputStream recieveData = new ObjectInputStream(connection.getInputStream());
response = (Serializable) recieveData.readObject();

System.out.println(response);

recieveData.close();


And this is my server code with spring to receive the request and send back response



@ResponseBody
@RequestMapping(value="/upload", method=RequestMethod.POST)
public Serializable fileUploadHandler(@RequestBody FilePacket packet, HttpServletRequest request, HttpSession session, HttpServletResponse response){

// handle request

return "response";
}


While running the code with above configuration, upon sending the request to server, I get Http error 415



java.io.IOException: Server returned HTTP response code: 415 for URL:


I removed @RequestBody and replaced it with



FilePacket packet = (FilePacket) new ObjectInputStream(request.getInputStream()).readObject();


and the request part was good. But then after a request I got the 406



java.io.IOException: Server returned HTTP response code: 415 for URL:


and so I replaced @ResponseBody with



new ObjectOutputStream(response.getOutputStream()).writeObject("response");


and then everything was good.


I've used these annotations with ajax and they work like charm but with java.net , I'm getting unsupported media type (415) and not acceptable (406). Is spring not able to read the request and send proper response or I'm missing something here? Is there a way to make it work?


Note: The class FilePacket is Serializable, one of whose fields is of type byte[] which holds the file data.


Aucun commentaire:

Enregistrer un commentaire