How to make POST with parameters in Webservice REST in java?

Asked

Viewed 14,854 times

3

Hello, I have a problem that I haven’t been able to solve for days.

The situation is as follows, until today I only managed to use the GET method of my webservice by passing parameters directly to the path of the URL. But now I need to consume the webservice by passing a parameter that is a String JSON for the webserice to validate this JSON and return me the data I need in another JSON via POST method.

Webservice POST method code:

@POST
@Produces("application/json")
@Path("/VerificaID")
@Consumes(MediaType.APPLICATION_JSON)
public String getDados(@QueryParam("id_senha_uev") String id_senha_uev){

   Uev uev = new Uev();
   Gson gson = new Gson();
   java.lang.reflect.Type uevType = new TypeToken<Uev>() {}.getType();
   uev = gson.fromJson(id_senha_uev, uevType);


   Gson g = new Gson();

   if(uev.getID_Uev() == 123 && uev.getSenha() == 123){
       return g.toJson(DadosRequisitados);
   }
   else{
       return g.toJson(null);
   }

And here the client method:

    // HTTP GET request
private String sendGet(String Url, String Json) throws Exception {

        try{
            URL targetUrl = new URL(null, Url, new sun.net.www.protocol.https.Handler());

        HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();

        httpConnection.setDoOutput(true);

        httpConnection.setRequestMethod("POST");

        httpConnection.setRequestProperty("Accept", "application/json");

        String input = Json;

        OutputStream outputStream = httpConnection.getOutputStream();

        outputStream.write(input.getBytes());

        outputStream.flush();

            if (httpConnection.getResponseCode() != 443) {
                throw new RuntimeException("Failed : HTTP error code : " + httpConnection.getResponseCode());
            }

            BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream())));
            String output;
            System.out.println("Output from Server:\n");

            while ((output = responseBuffer.readLine()) != null) {
                System.out.println(output);
            }

            httpConnection.disconnect();
            responseBuffer.close();

            return responseBuffer.toString();

          }catch(MalformedURLException e) {
            e.printStackTrace();
          }catch (IOException e) {
            e.printStackTrace();
         }
        return null;
}

Someone would know how to send a parameter for the authentication in the webservice and it returns the data to me, without using the absolute path of the URL?

Thanks in advance.

  • How does this authentication work or should work? Just send a JSON and get the answer or are you trying to use something more complex such as basic-Authorization, Digest or Oauth?

  • The Uev object has id and password as attributes, the json has id and password for authentication, all I want to do is authenticate this json and if validated, return a string to the client that would be the requested data that he requested.

1 answer

4


Maybe this will help you:

public String sendPost(String url, String json) throws MinhaException {

    try {
        // Cria um objeto HttpURLConnection:
        HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection();

        try {
            // Define que a conexão pode enviar informações e obtê-las de volta:
            request.setDoOutput(true);
            request.setDoInput(true);

            // Define o content-type:
            request.setRequestProperty("Content-Type", "application/json");

            // Define o método da requisição:
            request.setRequestMethod("POST");

            // Conecta na URL:
            request.connect();

            // Escreve o objeto JSON usando o OutputStream da requisição:
            try (OutputStream outputStream = request.getOutputStream()) {
                outputStream.write(json.getBytes("UTF-8"));
            }

            // Caso você queira usar o código HTTP para fazer alguma coisa, descomente esta linha.
            //int response = request.getResponseCode();

            return readResponse(request);
        } finally {
            request.disconnect();
        }
    } catch (IOException ex) {
        throw new MinhaException(ex);
    }
}

private String readResponse(HttpURLConnection request) throws IOException {
    ByteArrayOutputStream os;
    try (InputStream is = request.getInputStream()) {
        os = new ByteArrayOutputStream();
        int b;
        while ((b = is.read()) != -1) {
            os.write(b);
        }
    }
    return new String(os.toByteArray());
}

public static class MinhaException extends Exception {
    private static final long serialVersionUID = 1L;

    public MinhaException(Throwable cause) {
        super(cause);
    }
}
  • 1

    Caraa Muitoooo thank you! You saved my life. I made it. For several days I researched about this type of parameter passage and could not at all, the codes were always similar and never worked. Your code became simple and functional, thank you very much Victor, saved me.

  • I have tried to see in several videos, I have looked everywhere, but nothing has helped me much in my problem, I would like to understand what I am doing wrong, I do not know if it is in the POST method there in webservice or in sendPost in consumption... PS: sendPost I copied yours from up here and still yes from error, so it should be my POST method on Webservice...

  • >>>>>@POST @Path("Product/post") @Consumes(Mediatype.APPLICATION_JSON) @Produces(Mediatype.APPLICATION_JSON) public Boolean insertProduct(@Queryparam("json") String json) { if (json.isEmpty() || json.equals("")) { Return false; } Product product = new Gson(). fromJson(json, Product.class); Return new Productodao(). inProduct(product); }

  • @Jonathancr I suggest you ask a new question.

  • I managed, I did several tests with the POST method on WS and there was the problem, I removed the @Produces and changed the @QueryParam for @PathParam and it worked xD vlw

Browser other questions tagged

You are not signed in. Login or sign up in order to post.