How to persist a record in the webservice database through restful Java?

4

I already have a method that takes a json and persists in the Mysql database. I can test it by the interface created by Netbeans, which has a field for inserting a json, but how do I, within a java application, make an http request by passing json as a parameter to be persisted? >

Method used for data persistence:

@PUT
@Consumes("application/json")
public void putJson(String json) throws Exception{
    Cliente cliente;
    Gson gson = new Gson();

    java.lang.reflect.Type tipo = new TypeToken<Cliente>(){}.getType();

    cliente = gson.fromJson(json, tipo);

    Conexao con = new Conexao();
    con.conexao();

    PreparedStatement ps = con.con.prepareStatement("insert into cliente values(?,?)");
    ps.setString(1, cliente.getCnpj());
    ps.setString(2, cliente.getRazao_social());
    ps.execute();

}

Thanks in advance!

    
asked by anonymous 06.09.2015 / 07:06

1 answer

2

I advise you to use AngularJS, it's very practical and easy to learn, I've set an example for you at JsFiddle .

In this example I showed how to consume a REST API by the GET method, I know you need a POST, but I did not find an ENDPOINT POST available to make the example, but I believe that the code of a GET example will help you to conceptualize on angular, then in the end I give an example of POST. Okay?

Here's the code and its the explanations:

Javascript File

var app = angular.module('myApp', []);
app.controller('HtmlController',['$scope', '$http', function ($scope, $http) {
    var endpoint = 'http://162.243.233.191:3000/api/ip';
    $scope.buscarJson = function () {
        $http.get(endpoint).success(function (data) {
            $scope.json = data;
        }).error(function (error) {
            console.error(error);
        });
    };
}]);

Here we create our angular module called myApp , then we create a controller that we will use in our HTML screen called HtmlController .

Angle works with dependency injection control

06.09.2015 / 17:46