Salve a tutti,
sto realizzando un Web Service RESTful in Java e ho bisogno di poter ricevere un oggetto JSON e ricrearne un altro come risposta.
Sto usando Gson per la (de)serializzazione del POJO di esempio.
per ora il codice che sto usando è più o meno questo:
Servizio REST
codice:
@POST
@Path("soggetti/{filtro}")
@Consumes("application/json")
public String ricercaSoggetti(@PathParam("filtro") String filtro,
@Context HttpHeaders headers) {
String elencoSoggetti = "";
System.out.println("Filtro passato " + filtro);
Gson gsong = new Gson();
SoggettoFiltro soggettoFiltro = gsong.fromJson(filtro, SoggettoFiltro.class);
elencoSoggetti = gsong.fromJson(soggettoFiltro);
System.out.println("Elenco soggetti " + elencoSoggetti);
return elencoSoggetti;
}
Client di test
codice:
public class TestRicercaSoggetto {
public static void main(String[] args) {
try {
SoggettoFiltro filtro = new SoggettoFiltro();
filtro.setCodiceSoggetto("44482");
String filtroJson = "";
Gson gson = new Gson();
filtroJson = gson.toJson(filtro);
// filtroJson = filtroJson.replace("\"", "\\\"");
URL url = new URL("http://localhost:8080/RestServices/rest/s/soggetti");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
os.write(filtroJson);
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Qualcuno sai dirmi come fare? Un riferimento (PDF?) da seguire, con ho ancora ben chiaro dove sbaglio...
Thx