Error sending json parameters by the PUT method in WebService client with java and jersey

3

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!

    
asked by Camilo Calderón Tapia 15.09.2017 в 18:34
source

1 answer

1

I see details in both codes in php and java: In php with slim framework I do something like this (see as steps parametros):

require ('Slim/Slim.php');
\Slim\Slim::registerAutoloader();
$app=new \Slim\Slim();
$app->get('/json/obtenerEmpleado/:id',function($id){
    $empleados=new ArrayObject();
    inicializar($empleados);
    $empleadoEncontrado=new Empleado();
    foreach ($empleados as $empleado){
        if ($empleado->id==$id){
            $empleadoEncontrado=$empleado;
        }
    }
    echo json_encode($empleadoEncontrado);
});
$app->run();

I do not do things like this $put=$app->request()->put(); and I do not see that here $app->put('/setCancion/', function () use ($app) a parameter is received since $app is outside the function and also in the url the variable has no name as in my example : :id .

Now on the Java side, fix the URL as armo. The parameters are separated with / and do not have a name, they are accommodated by position:

public void insertar(){
    BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
    try {
        System.out.println("Ingrese el nuevo Id: ");
        String id = br.readLine();
        System.out.println("Ingrese el nuevo nombre: ");
        String nombre = br.readLine();
        System.out.println("Ingrese el nuevo puesto: ");
        String puesto = br.readLine();
        String url="http://localhost:8080/XXXXX/restful/empleados/insertar/"+URLEncoder.encode(id,"UTF-8")+"/"+URLEncoder.encode(nombre,"UTF-8")+"/"+URLEncoder.encode(puesto,"UTF-8");
        //insertar es el nombre del método en php
        URL urlObj=new URL(url);
        //abrimos la conexion
        HttpURLConnection conexion=(HttpURLConnection)urlObj.openConnection();
        conexion.setRequestMethod("PUT");
        conexion.connect();
        //Almacenamos la respuesta
        System.out.println(conexion.getResponseMessage());
        //System.out.println(resultado);
        conexion.disconnect();//desconecto la url
    } catch (Exception e) {
        e.printStackTrace();
    }
}

and be careful to send the characters that it says in the specification of the URLs as they are prohibited .

    
answered by 09.10.2017 в 21:03