How to do POST with parameters in WebService REST in java?

2

Hello, I have a problem that I can not solve for days.

The situation is as follows, until today I was only able to use the GET method of my webservice passing parameters directly to the URL path. But now I need to consume the webservice by passing a parameter that is a String JSON so that the webserice validates this JSON and returns the data I need in another JSON via the 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 is 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;
}

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

Thank you in advance.

    
asked by anonymous 10.11.2015 / 15:03

1 answer

3

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);
    }
}
    
10.11.2015 / 16:18