Browse Source

[Refactoring] nouveau code avec okHtpp et JSONObject

master
art.dambrine 5 years ago
parent
commit
861eeb5ce8
  1. BIN
      app/libs/gson-2.8.6-javadoc.jar
  2. BIN
      app/libs/gson-2.8.6.jar
  3. 150
      app/src/main/java/com/speculos/myapplicationoc/APICommandes.java
  4. 92
      app/src/main/java/com/speculos/myapplicationoc/JsonTraductor.java
  5. 2
      app/src/main/java/com/speculos/myapplicationoc/MyApplication.java
  6. 91
      app/src/main/java/com/speculos/myapplicationoc/PaymentActivity.java
  7. 100
      app/src/main/java/com/speculos/myapplicationoc/TagDetectedActivity.java
  8. 55
      app/src/main/java/com/speculos/myapplicationoc/TagDetectedActivityAdmin.java
  9. 13
      app/src/main/java/com/speculos/myapplicationoc/ThreadPing.java

BIN
app/libs/gson-2.8.6-javadoc.jar

Binary file not shown.

BIN
app/libs/gson-2.8.6.jar

Binary file not shown.

150
app/src/main/java/com/speculos/myapplicationoc/APICommandes.java

@ -1,150 +0,0 @@
package com.speculos.myapplicationoc;
import android.os.StrictMode;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class APICommandes {
private static HttpURLConnection con;
private static String response;
private static int SDK_INT = android.os.Build.VERSION.SDK_INT;
/*
A propos de l'implementation JWT :
Using the token
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Authorization", "Bearer " + accessToken);
*/
static String getMethod(String url) throws IOException {
if (SDK_INT > 8) /*Eviter l'erreur android qui empêche call API dans le main thread*/
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your codes here
}
try {
URL myurl = new URL(url);
Log.d("API-debug","GET sur myurl: "+url);
con = (HttpURLConnection) myurl.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setRequestMethod("GET");
StringBuilder content;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = in.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
response = content.toString();
} catch (Exception e){
// handle exception here
Log.d("API-debug","Exception, GET a echoue, we return empty string");
return "";
} finally {
con.disconnect();
}
return response;
}
public static String postMethod(String url, String urlParameters) throws IOException {
/*
Exemple de paramètres pour faire un POST :
String urlParameters = "{\"name\": \"user4\", \"solde\": 22, \"email\": \"user4@mail.fr\"}";
*/
if (SDK_INT > 8) /*Eviter l'erreur android qui empêche call API dans le main thread*/
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your codes here
}
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
try {
URL myurl = new URL(url);
con = (HttpURLConnection) myurl.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Java client");
con.setRequestProperty("Content-Type", "application/json");
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(postData);
}
StringBuilder content;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = br.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
//System.out.println(content.toString());
response = content.toString();
} catch (Exception e) {
Log.d("API-debug","Exception, le call POST echoue");
} finally {
con.disconnect();
}
return response;
}
}

92
app/src/main/java/com/speculos/myapplicationoc/JsonTraductor.java

@ -1,92 +0,0 @@
package com.speculos.myapplicationoc;
import android.util.Log;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
public class JsonTraductor {
private String json;
private List<JsonObject> listJson = new ArrayList<JsonObject>();
public JsonTraductor(){
// Json de test
// {"id":1,"nfcId":"azerty","client":{"id":1,"name":"Omer"},"state":1}
// "[{\"id\":1,\"nfcId\":\"azerty\",\"client\":{\"id\":1,\"name\":\"Omer\"},\"state\":1},{\"id\":2,\"nfcId\":\"oui\",\"client\":null,\"state\":0}]";
json = "{\"id\":1,\"nfcId\":\"azerty\",\"client\":{\"id\":1,\"name\":\"Omer\"},\"state\":1}";
}
JsonTraductor(String jsonEntry){
json = jsonEntry;
buildList();
}
private void buildList(){
// Parse le json et tiens à jour une liste d'objets json
listJson.clear();
try {
if(jsonIsArray(json)){
JsonArray entries = (JsonArray) new JsonParser().parse(json);
//String id = ((JsonObject)entries.get(0)).get("id").toString();
//System.out.println(id);
for(int i = 0; i<entries.size(); i++){
listJson.add(((JsonObject)entries.get(i)));
}
} else {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(json);
JsonObject jsonObjectOne = jsonElement.getAsJsonObject();
//System.out.println(jsonObject.get("id"));
listJson.add(jsonObjectOne);
//System.out.println(listJson.get(0).get("id"));
}
} catch (Exception e){
// handle exception here
}
}
private static Boolean jsonIsArray(String json){
Log.d("JsonTraductor-debug","Json: "+json);
if (json != null){
return json.toCharArray()[0] != '{';
} else {
return false;
}
}
String getJsonData(String jsonId, int jsonIndex){
if(jsonIndex >= listJson.size()){
// pour ne pas depasser l'index final
return null;
} else {
return listJson.get(jsonIndex).get(jsonId).toString();
}
}
}

2
app/src/main/java/com/speculos/myapplicationoc/MyApplication.java

@ -6,9 +6,7 @@ public class MyApplication extends Application {
private String serverURL = "http://art-dev:8080"; private String serverURL = "http://art-dev:8080";
public String getServerURL(){ public String getServerURL(){
return serverURL; return serverURL;
} }
} }

91
app/src/main/java/com/speculos/myapplicationoc/PaymentActivity.java

@ -12,23 +12,35 @@ import android.widget.Toast;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException; import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PaymentActivity extends AppCompatActivity { public class PaymentActivity extends AppCompatActivity {
static String hexa_id, title, soldeString; static String hexa_id, title, soldeString, srvURL;
static float solde; static float solde;
// recuperation de MyApplication contenant les variables globales
MyApplication myApplication = (MyApplication) getApplication();
String srvURL = myApplication.getServerURL();
// Temporaire // Temporaire
static String nfcId = "azerty"; // static String nfcId = "azerty";
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
// recuperation de MyApplication contenant les variables globales
MyApplication myApplication = (MyApplication) getApplication();
srvURL = myApplication.getServerURL();
// Load le layout
setContentView(R.layout.activity_payment); setContentView(R.layout.activity_payment);
hexa_id = getIntent().getStringExtra("hexa_id"); hexa_id = getIntent().getStringExtra("hexa_id");
@ -97,10 +109,34 @@ public class PaymentActivity extends AppCompatActivity {
} else { } else {
// Call API Paiement // Call API Paiement
try { try {
String response = APICommandes.postMethod(srvURL + "/api/payment","{\"nfcId\": \"" + nfcId + "\", \"price\": " + transaction_value + "}");
Log.d("PAYMENT-debug",response); OkHttpClient client = new OkHttpClient().newBuilder()
} catch (IOException e) { .build();
Toast.makeText(PaymentActivity.this, "Pas assez d'argent!", Toast.LENGTH_LONG).show(); MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"nfcId\": \"" + hexa_id + "\",\"price\": " + transaction_value + "}\n");
Request request = new Request.Builder()
.url(srvURL + "/api/payment")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
Log.d("PAYMENT-debug", response.body().toString());
JSONObject jsonReader = null;
jsonReader = new JSONObject(response.body().string());
String message = jsonReader.getString("message");
if (response.code() == 200) {
// Paiement effectué
Toast.makeText(PaymentActivity.this, message, Toast.LENGTH_LONG).show();
finish();
} else if (response.code() == 406) {
Toast.makeText(PaymentActivity.this, message, Toast.LENGTH_LONG).show();
}
} catch (IOException | JSONException e) {
Toast.makeText(PaymentActivity.this, "Erreur lors de la connexion au serveur", Toast.LENGTH_LONG).show();
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -109,10 +145,38 @@ public class PaymentActivity extends AppCompatActivity {
} else { } else {
//Call API Rechargement //Call API Rechargement
try { try {
String response = APICommandes.postMethod(srvURL + "/api/load","{\"nfcId\": \"" + nfcId + "\", \"price\": " + transaction_value + "}"); // String response = APICommandes.postMethod(srvURL + "/api/load","{\"nfcId\": \"" + hexa_id + "\", \"price\": " + transaction_value + "}");
Log.d("PAYMENT-debug",response);
} catch (IOException e) { OkHttpClient client = new OkHttpClient().newBuilder()
Toast.makeText(PaymentActivity.this, "Erreur rechargement!", Toast.LENGTH_LONG).show(); .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"nfcId\": \"" + hexa_id + "\",\"price\": " + transaction_value + "}\n");
Request request = new Request.Builder()
.url(srvURL + "/api/load")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
Log.d("PAYMENT-debug", response.body().toString());
JSONObject jsonReader = null;
jsonReader = new JSONObject(response.body().string());
String message = jsonReader.getString("message");
if (response.code() == 200) {
// Rechargement effectué
Toast.makeText(PaymentActivity.this, message, Toast.LENGTH_LONG).show();
finish();
} else if (response.code() == 406) {
Toast.makeText(PaymentActivity.this, message, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(PaymentActivity.this, "Erreur rechargement! " + message, Toast.LENGTH_LONG).show();
}
} catch (IOException | JSONException e) {
Toast.makeText(PaymentActivity.this, "Erreur lors de la connexion au serveur", Toast.LENGTH_LONG).show();
e.printStackTrace(); e.printStackTrace();
} }
@ -120,7 +184,6 @@ public class PaymentActivity extends AppCompatActivity {
} }
} }
}); });

100
app/src/main/java/com/speculos/myapplicationoc/TagDetectedActivity.java

@ -3,29 +3,39 @@ package com.speculos.myapplicationoc;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class TagDetectedActivity extends Activity { public class TagDetectedActivity extends Activity {
String hexa_id, mail; String hexa_id, mail, srvURL;
float solde = 0; float solde = 0;
String srvURL;
// Temporaire
String nfcId = "azerty";
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
// Tweak pour contourner l'erreur android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// recuperation de MyApplication contenant les variables globales // recuperation de MyApplication contenant les variables globales
MyApplication myApplication = (MyApplication) getApplication(); MyApplication myApplication = (MyApplication) getApplication();
srvURL = myApplication.getServerURL(); srvURL = myApplication.getServerURL();
@ -47,31 +57,51 @@ public class TagDetectedActivity extends Activity {
String stringAPI = ""; String stringAPI = "";
try { try {
stringAPI = APICommandes.getMethod(srvURL + "/api/bracelets.json?nfcId="+ nfcId);
Log.d("API-debug",stringAPI);
} catch (IOException e) {
e.printStackTrace();
}
JsonTraductor maListeJson = new JsonTraductor(stringAPI); OkHttpClient client = new OkHttpClient().newBuilder()
maListeJson = new JsonTraductor(maListeJson.getJsonData("client", 0)); .connectTimeout(2000, TimeUnit.MILLISECONDS)
.callTimeout(2000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url(srvURL + "/api/bracelets.json?nfcId=" + hexa_id)
.method("GET", null)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
if( (mail = maListeJson.getJsonData("email", 0)) != null ){ String in = response.body().string();
in = in.substring(1, in.length() - 1); // on retire le [] autour de notre json premier et dernier char
Log.d("API-debug-in", in);
mail = mail.substring(1,mail.length()-1); JSONObject jsonObject = null;
} else {
mail = "-";//Assign default string try {
jsonObject = new JSONObject(in);
jsonObject = new JSONObject(jsonObject.get("client").toString()); // recup client embed dans l'objet parent
} catch (JSONException e) {
Log.d("API-debug", e.getMessage());
} }
String mail = null;
mail = jsonObject.getString("email");
solde = Float.parseFloat(jsonObject.getString("solde"));
TextView value_mail = findViewById(R.id.value_mail); TextView value_mail = findViewById(R.id.value_mail);
value_mail.setText(mail); value_mail.setText(mail);
try {solde = Float.parseFloat(maListeJson.getJsonData("solde", 0));} catch(Exception e) { solde = 0;}
TextView value_solde = findViewById(R.id.value_solde);
value_solde.setText(solde+" €");
} catch (IOException | JSONException e) {
e.printStackTrace();
Log.d("API-debug-exception", e.getMessage());
Toast.makeText(TagDetectedActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
finish();
}
TextView value_solde = findViewById(R.id.value_solde);
value_solde.setText(solde + " €");
Button button_payer = findViewById(R.id.button_enregistrer); Button button_payer = findViewById(R.id.button_enregistrer);
@ -106,19 +136,39 @@ public class TagDetectedActivity extends Activity {
super.onResume(); super.onResume();
// code à la fermeture de myIntent // code à la fermeture de myIntent
String stringAPI2 = "";
try { try {
stringAPI2 = APICommandes.getMethod(srvURL + "/api/bracelets.json?nfcId="+ nfcId);
Log.d("API-debug",stringAPI2); OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(2000, TimeUnit.MILLISECONDS)
.callTimeout(2000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url(srvURL + "/api/bracelets.json?nfcId=" + hexa_id)
.method("GET", null)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
String in = response.body().string();
in = in.substring(1, in.length() - 1);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(in);
jsonObject = new JSONObject(jsonObject.get("client").toString()); // recup client embed dans l'objet parent
solde = Float.parseFloat(jsonObject.getString("solde"));
} catch (JSONException e) {
Log.d("API-debug", e.getMessage());
}
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
JsonTraductor maListeJson = new JsonTraductor(stringAPI2);
maListeJson = new JsonTraductor(maListeJson.getJsonData("client", 0));
try{solde = Float.parseFloat(maListeJson.getJsonData("solde", 0));} catch(Exception e){solde = 0;}
TextView value_solde = findViewById(R.id.value_solde); TextView value_solde = findViewById(R.id.value_solde);
value_solde.setText(solde + " €"); value_solde.setText(solde + " €");
} }

55
app/src/main/java/com/speculos/myapplicationoc/TagDetectedActivityAdmin.java

@ -2,6 +2,7 @@ package com.speculos.myapplicationoc;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.widget.Button; import android.widget.Button;
@ -15,6 +16,7 @@ import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import okhttp3.MediaType; import okhttp3.MediaType;
@ -27,24 +29,27 @@ public class TagDetectedActivityAdmin extends Activity {
String hexa_id, mail, username, srvURL; String hexa_id, mail, username, srvURL;
// recuperation de MyApplication contenant les variables globales
// MyApplication myApplication = (MyApplication) getApplication();
// Temporaire
// String nfcId = "azerty";
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
// Tweak pour contourner l'erreur android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Récupération MyApplication contenant les variables globales
MyApplication myApplication = (MyApplication) getApplication(); MyApplication myApplication = (MyApplication) getApplication();
srvURL = myApplication.getServerURL(); srvURL = myApplication.getServerURL();
// Setup de la vue à partir du layout
setContentView(R.layout.activity_tag_detected_admin); setContentView(R.layout.activity_tag_detected_admin);
hexa_id = getIntent().getStringExtra("hexa_id"); hexa_id = getIntent().getStringExtra("hexa_id");
if (hexa_id == null) { if (hexa_id == null) {
hexa_id = "-";//Assign default string //Assign default string
hexa_id = "-";
} }
TextView value_NFCID = findViewById(R.id.value_NFCID); TextView value_NFCID = findViewById(R.id.value_NFCID);
@ -57,10 +62,12 @@ public class TagDetectedActivityAdmin extends Activity {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
if (hexa_id.equals("-")) return; // si hexa_id non définit return onClick
// Vérifications et Call API créer le compte // Vérifications et Call API créer le compte
EditText value_mail = findViewById(R.id.value_mail); EditText value_mail = findViewById(R.id.value_mail);
mail = value_mail.getText().toString(); mail = value_mail.getText().toString();
username = mail.subSequence(0,mail.indexOf("@")).toString(); if (mail.length() > 0) username = mail.subSequence(0, mail.indexOf("@")).toString();
// Validation du champ email // Validation du champ email
String regex = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"; String regex = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
@ -69,29 +76,45 @@ public class TagDetectedActivityAdmin extends Activity {
if (pattern.matcher(mail).matches()) { if (pattern.matcher(mail).matches()) {
// L'email est validé par la regex on va pouvoir préparer la requête de verif si compte existe // L'email est validé par la regex on va pouvoir préparer la requête de verif si compte existe
// Call l'API pour voir si un client avec ce mail existe // Call l'API pour voir si un client avec ce mail existe
String apiResponse = "";
Response apiResponse = null;
String strReponse = "";
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(2000, TimeUnit.MILLISECONDS)
.callTimeout(2000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url(srvURL + "/api/clients.json?email=" + mail)
.method("GET", null)
.build();
try { try {
apiResponse = APICommandes.getMethod(srvURL + "/api/clients.json?email=" + mail); apiResponse = client.newCall(request).execute();
Log.d("API-CLIENT-DEBUG", "api:" + apiResponse.code());
strReponse = apiResponse.body().string();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
Log.d("API-CLIENT-DEBUG", "Server not responding");
Toast.makeText(TagDetectedActivityAdmin.this, "Server not responding", Toast.LENGTH_LONG).show();
return;
} }
if(apiResponse.length() <=3 ) {
if (strReponse.length() <= 3 && strReponse.length() > 0) {
// Le mail n'est pas présent créer un nouveau compte. // Le mail n'est pas présent créer un nouveau compte.
Toast.makeText(TagDetectedActivityAdmin.this, "Création de compte NFC Cashless, mail:" + mail + " name:" + username + " bracelet:" + hexa_id, Toast.LENGTH_LONG).show(); Toast.makeText(TagDetectedActivityAdmin.this, "Création de compte NFC Cashless, mail:" + mail + " name:" + username + " bracelet:" + hexa_id, Toast.LENGTH_LONG).show();
Response responseHttp = null; Response responseHttp = null;
try { try {
// response = APICommandes.postMethod(srvURL + "/api/clients","{\"name\": \"" + username + "\", \"email\": \"" + mail + "\", \"solde\" :"+0+"}");
OkHttpClient client = new OkHttpClient().newBuilder() client = new OkHttpClient().newBuilder()
.build(); .build();
MediaType mediaType = MediaType.parse("application/json"); MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"name\": \"" + username + "\",\"email\": \"" + mail + "\",\"solde\": 0}"); RequestBody body = RequestBody.create(mediaType, "{\"name\": \"" + username + "\",\"email\": \"" + mail + "\",\"solde\": 0}");
Request request = new Request.Builder() request = new Request.Builder()
.url(srvURL + "/api/clients") .url(srvURL + "/api/clients")
.method("POST", body) .method("POST", body)
.addHeader("Content-Type", "application/json") .addHeader("Content-Type", "application/json")
@ -109,7 +132,6 @@ public class TagDetectedActivityAdmin extends Activity {
} else { } else {
/*Creation du compte réussie, link le bracelet au compte client (TODO: penser à faire les verifs si bracelet existe avant de créer un compte client) /*Creation du compte réussie, link le bracelet au compte client (TODO: penser à faire les verifs si bracelet existe avant de créer un compte client)
Une fois qu'on a vérifié que le bracelet n'existe pas dans la base on l'ajoute au client Une fois qu'on a vérifié que le bracelet n'existe pas dans la base on l'ajoute au client
On commence par parser la reponse de l'appel POST précédent pour avoir l'idClient sans refaire de requête*/ On commence par parser la reponse de l'appel POST précédent pour avoir l'idClient sans refaire de requête*/
@ -125,16 +147,15 @@ public class TagDetectedActivityAdmin extends Activity {
} }
// On peut maintenant link le bracelet grace à l'hexa_id et l'idClient // On peut maintenant link le bracelet grace à l'hexa_id et l'idClient
try { try {
OkHttpClient client = new OkHttpClient().newBuilder() client = new OkHttpClient().newBuilder()
.build(); .build();
MediaType mediaType = MediaType.parse("application/json"); MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"nfcId\": \"" + hexa_id + "\",\"client\": \"/api/clients/" + idClient + "\",\"state\": 0}"); RequestBody body = RequestBody.create(mediaType, "{\"nfcId\": \"" + hexa_id + "\",\"client\": \"/api/clients/" + idClient + "\",\"state\": 0}");
Request request = new Request.Builder() request = new Request.Builder()
.url(srvURL + "/api/bracelets") .url(srvURL + "/api/bracelets")
.method("POST", body) .method("POST", body)
.addHeader("Content-Type", "application/json") .addHeader("Content-Type", "application/json")

13
app/src/main/java/com/speculos/myapplicationoc/ThreadPing.java

@ -2,6 +2,10 @@ package com.speculos.myapplicationoc;
import java.io.IOException; import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class ThreadPing extends Thread { public class ThreadPing extends Thread {
@ -32,7 +36,14 @@ public class ThreadPing extends Thread {
try { try {
String apiResponse = ""; String apiResponse = "";
try { try {
apiResponse = APICommandes.getMethod(url + "/api"); OkHttpClient client = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url(url + "/api")
.method("GET", null)
.build();
Response response = client.newCall(request).execute();
apiResponse = response.body().toString();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();

Loading…
Cancel
Save