I have a WebService client side application in JAVA and server side in PHP.
I am trying to send a request with json parameters by CURL command as seen below:
curl -H 'Content-Type:application/json' -X PUT -d path=4920 -d message="I love you" http://localhost:4321/idjserver/index.php/setCancion/
The WebService is built in SlimFrameWork in the following way:
<?php
header('Access-Control-Allow-Origin: *');
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->put('/setCancion/', function () use ($app) {
$put=$app->request()->put();
var_dump($put);
});
$app->run();
So the response of the CURL command is:
Answer CURL:
array(2) {
["path"]=>
string(4) "4920"
["message"]=>
string(7) "I love you"
}
The CURL command behaves as expected, but on the other hand I have JAVA client with Jersey where I can not send the json parameters correctly, I'm trying with two different forms, this is my code:
package idjplaymp4;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientResponse;
public class ClienteServicioWeb {
private static final String servicePath= "http://localhost:4321/idjserver/index.php";
private Client client = null;
private WebTarget target = null;
private final Gson gson = new Gson();
public ClienteServicioWeb() {
client = ClientBuilder.newClient();
target = client.target(servicePath);
}
/**** Get Request *****/
public Genero[] getMenu()
{
String menu = target.path("/getMenu").request(MediaType.APPLICATION_JSON).get(String.class);
Genero[] g = gson.fromJson(menu, Genero[].class);
return g;
}
/*** PRIMER FORMA *************/
public void addSong(String songPath){
JsonObject inputJsonObj = new JsonObject();
inputJsonObj.addProperty("path", songPath);
inputJsonObj.addProperty("message", "Hello World");
System.out.println(target.path("/setCancion/").request(MediaType.APPLICATION_JSON)
.put(Entity.entity(inputJsonObj,MediaType.APPLICATION_JSON), JsonObject.class));
}
/*** SEGUNDA FORMA *************/
public void addSong(String songPath){
String parametros="{\"path\":\""+songPath+"\"}";
String result = target.path("/setCancion/")
.request(MediaType.APPLICATION_JSON)
.put(Entity.entity(parametros, MediaType.APPLICATION_JSON), String.class);
System.out.println("Result: "+result);
}
}
the FIRST FORM returns the following error:
MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class com.google.gson.JsonObject, genericType=class com.google.gson.JsonObject.
The SECOND FORM returns an empty array:
Result: array(0) {
}
Can someone give me a hand!