added initial http method and login task

This commit is contained in:
aj 2020-01-31 22:30:28 +00:00
parent 3c3cd8a08b
commit f597cf6456
3 changed files with 169 additions and 54 deletions

View File

@ -1,6 +1,5 @@
package com.example.applogin;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
@ -11,30 +10,13 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.ConnectException;
import java.util.HashMap;
import java.util.Map;
import com.example.applogin.network.LoginTask;
import java.util.concurrent.ExecutionException;
public class Login2Activity extends AppCompatActivity {
@ -96,44 +78,31 @@ public class Login2Activity extends AppCompatActivity {
private void tryLogin(String username, String password) {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://ev-scheduler.appspot.com/api/auth/login";
LoginTask task = new LoginTask(username, password);
task.execute();
HashMap<String, String> dict = new HashMap<>();
dict.put("username", username);
dict.put("password", password);
JSONObject json = new JSONObject(dict);
try {
String result = task.get();
// Request a string response from the provided URL.
final JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
//Toast.makeText(Login2Activity.this, response.getString("token"), Toast.LENGTH_SHORT).show();
//System.out.println(response.toString());
SharedPreferences context = getApplicationContext().getSharedPreferences("scheduler_preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = context.edit();
editor.putString("api_key", response.getString("token"));
editor.apply();
Intent myIntent = new Intent(Login2Activity.this, JoinQueueActivity.class);
startActivity(myIntent);
}catch(JSONException e){
//could put an error message here
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(Login2Activity.this, Integer.toString(error.networkResponse.statusCode), Toast.LENGTH_SHORT).show();
//Put error message (failed login, 3 different messages)
//if error.networkResponse.statusCode == 401 , message wrong password (auth_blueprint.py)
if (result == null) {
Toast.makeText(Login2Activity.this, "error", Toast.LENGTH_SHORT).show();
}else{
SharedPreferences context = getApplicationContext().getSharedPreferences("scheduler_preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = context.edit();
editor.putString("api_key", result);
editor.apply();
Intent myIntent = new Intent(Login2Activity.this, JoinQueueActivity.class);
startActivity(myIntent);
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

View File

@ -0,0 +1,109 @@
package com.example.applogin.network;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.net.URL;
import java.net.HttpURLConnection;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class AbstractNetworkTask<X, Y, Z> extends AsyncTask<X, Y, Z> {
private static final int READ_TIMEOUT = 15000;
private static final int CONNECTION_TIMEOUT = 15000;
protected class Result {
public JSONObject response;
public int statusCode;
}
public enum HTTPMethod {
GET, POST, PUT, DELETE
}
protected String getAPIUrl(String suffix){
return "https://ev-scheduler.appspot.com/" + suffix;
}
protected Result makeAuthenticatedRequest(String url, HTTPMethod method, HashMap<String, String> params, HashMap<String, String> headers, String api_key){
if (headers == null) {
headers = new HashMap<>();
}
headers.put("Authorization", "Bearer " + api_key);
return makeRequest(url, method, params, headers);
}
protected Result makeRequest(String url, HTTPMethod method, HashMap<String, String> params, HashMap<String, String> headers) {
Result result = new Result();
String inputLine;
HttpURLConnection connection = null;
try {
//Create a URL object holding our url
URL myUrl = new URL(url);
connection = (HttpURLConnection) myUrl.openConnection();
if(method == HTTPMethod.POST || method == HTTPMethod.PUT){
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; utf-8");
}
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getKey());
}
}
connection.setRequestMethod(method.toString());
connection.setRequestProperty("Accept", "application/json");
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.connect();
if(method == HTTPMethod.POST || method == HTTPMethod.PUT){
JSONObject body = new JSONObject(params);
OutputStream os = connection.getOutputStream();
byte[] input = body.toString().getBytes("utf-8");
os.write(input, 0, input.length);
os.flush();
os.close();
}
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result.statusCode = connection.getResponseCode();
result.response = new JSONObject(stringBuilder.toString());
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
finally {
if (connection != null) {
connection.disconnect();
}
}
return result;
}
}

View File

@ -0,0 +1,37 @@
package com.example.applogin.network;
import org.json.JSONException;
import java.util.HashMap;
public class LoginTask extends AbstractNetworkTask<Void, Void, String> {
private String username;
private String password;
public LoginTask(String username, String password){
super();
this.username = username;
this.password = password;
}
@Override
protected String doInBackground(Void... params) {
HashMap<String, String> body = new HashMap<>();
body.put("username", username);
body.put("password", password);
Result result = makeRequest(getAPIUrl("api/auth/login"), HTTPMethod.POST, body, null);
try {
if (200 <= result.statusCode && result.statusCode < 300)
return result.response.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}