Rest api in android
- By Juraj Puchký
- Android Development
- 3 Replies
Try this
then call for example API like this
In Activity you can call this
In PHP API server it can look like this.
Java:
public final class FromUrlHelper {
public static JSONObject getJSONObject(String url) throws IOException {
if (Constants.debug) Log.d("API Call", url);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(FromUrlHelper.getJSONFromUrl(url));
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
then call for example API like this
Java:
public class AuthService {
private static AuthService ourInstance = null;
public static AuthService getInstance() {
if (ourInstance == null) {
ourInstance = new AuthService();
}
return ourInstance;
}
private String currentSession;
private boolean loggined;
private AuthService() {
}
public boolean login(String email, String password) {
if (!email.isEmpty() && !password.isEmpty()) {
try {
JSONObject result = FromUrlHelper.getJSONObject(Constants.serviceBaseUrl + "login?email=" + email + "&password=" + password);
try {
int errorCode = result.getInt("errorCode");
if (errorCode == 0) {
this.currentSession = result.getString("sessionId");
loggined = true;
return true;
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public boolean logout() {
loggined = false;
this.currentSession = null;
return true;
}
}
In Activity you can call this
Code:
AuthService authService = AuthService.getInstance();
if(authService.login("email","password")) {
// do something
} else {
// do something
}
In PHP API server it can look like this.
PHP:
$customer = $this->entityManager->getRepository(Customer::class)->findOneBy(['email' => $request->get('email'), 'password' => md5($request->get('password')), 'eshop' => $eshop]);
if ($customer) {
/** @var Session $session */
$session = $this->getSessionFromCustomer($customer);
if(!$session) {
$sessionId = $this->createSession($customer);
} else {
$sessionId = $session->getCode();
}
$response->errorCode = self::ERR_OK;
} else {
$sessionId = null;
$response->errorCode = self::ERR_AUTH;
}
$response->sessionId = $sessionId;
return new JsonResponse($response);
