Check the Boolean return of php function in java

Asked

Viewed 245 times

0

I am developing a java application that requires a furlough to be activated. I’ve done the php function that checks the data in the database and returns a true if everything is right, or false if it goes wrong.

This function is in a url:

http://site.com.br/verificarlicenca

What I thought is in the java application send the license via GET to that url, which will look like this:

http://site.com.br/verificarlicenca?licenca=KEY

My function is taking this key and treating, checking if it is true and returning a Boolean.

In short, I need to send this parameter and also receive the return, IN JAVA, it is possible?

  • Is this return from a page that was generated from the result of the PHP function? Or do you want to read the PHP function from Java? Could you put more details in the question?

  • 1

    Sorry friend, I’ve updated the question.

  • I made a sketch code to give you a north, I won’t be able to answer this weekend, if no one answers by Monday I elaborate a response

  • Didn’t understand the while part, what is its functionality? How can I check the Boolean return?

  • You made a webservice in PHP. This means that Java does not have to worry about which language this information is being provided, only consuming the webservice. There’s a lot of questions here

1 answer

1

Following the same reasoning of @Denis Rudnei de Souza, you can read the content returned by the server (php page) following the instructions posted on github:

import java.io.*;
import java.net.*;

public class ReadLicence {

  public static String valida(String key) throws Exception {
    StringBuilder result = new StringBuilder();
    URL url = new URL("http://localhost:8000/a.php?licenca=" + key);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    //armazena os caracteres recebidos através da rede
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    //readline() permite ler uma linha (\n ou \n\r) do que foi retornada
    //como resposta pelo servidor (a partir do que está em bufferreader)
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    rd.close();
    return result.toString();
  }

  public static void main(String[] args) throws Exception {
    String chave = "123571113";
    //mensagem recebida do servidor true ou false
    String resultado = valida(chave);
    System.out.println(resultado);

    if(resultado.equals("true")){
      System.out.println("licença valida");
    }else {
      System.out.println("licença invalida");
    }
  }
}

I took the liberty of adding a few comments. In addition to the code posted by @Denis Rudnei de Souza, I added the treatment (not enough) to manipulate the server response. On the server I created a small scribe called a.php:

<?php
function valida_licenca($chave){
    if($chave == '123571113'){
        return 'true';
    }else{
        return 'false';
    }
  }

//a função licença retorna string pois caso fosse boolean 
//seria convertido para 0 ou 1
echo valida_licenca($_GET['licenca']);

With that I imagine it’s possible to solve your problem. Although it would be better for the server to return the json content (if you want to look for how to read java json with the library gson. There is an interesting tutorial here).

A server equivalent (PHP) for working with json would be:

<?php
function valida_licenca($chave){
    if($chave == '123571113'){
        return json_encode(['ativado' => true]);
    }else{
        return json_encode(['ativado' => false]);
    }
}

echo valida_licenca($_GET['licenca']);

And the java modifications would be:

import java.io.*;
import java.net.*;
import com.google.gson.Gson;

public class ReadLicence {

  public static String valida(String key) throws Exception {
    StringBuilder result = new StringBuilder();
    URL url = new URL("http://localhost:8000/a.php?licenca=" + key);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    //armazena os caracteres recebidos através da rede
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    //readline() permite ler uma linha (\n ou \n\r) do que foi retornada
    //como resposta pelo servidor (a partir do que está em bufferreader)
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    rd.close();
    return result.toString();
  }

  public static void main(String[] args) throws Exception {
    String chave = "123571113";
    //mensagem recebida do servidor true ou false
    String resultado = valida(chave);
    System.out.println(resultado);

    //a biblioteca json permite transformar um objeto json 
    //em um objeto java
    Gson gson = new Gson();
    //nesse caso no json retornado tem esse formato:
    //{ativado: boolean}. O valor do campo ativado é colocado
    //no atributo da classe Licenca, que tem o mesmo nome
    Licenca licenca = gson.fromJson(resultado, Licenca.class);
    System.out.println(licenca.ativado);

    if(licenca.ativado){
      System.out.println("licença valida");
    }else {
      System.out.println("licença invalida");
    }
  }

  private class Licenca{
    public Boolean ativado = null;
  }
}

The most complicated thing is to add the gson library to the classpath of your development environment. The jar can be downloaded here or directly here.

  • Thank you so much for the help friend, I will try here. There is some specific reason why the return would be better in json?

  • If you need to return some information beyond Boolean. Type {ativado: true, expira:'11-11-2011'}, it would be easier to access by following this format than having to explit in a string.

  • When it comes to security, what’s the best way? Because I just need to check the key anyway.

Browser other questions tagged

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