Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.henallux.parkeasy.DAO;
- import com.google.gson.Gson;
- import com.henallux.parkeasy.Model.User;
- import org.json.JSONObject;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class UserDAO {
- public static String TOKEN = "";
- private int responseCode;
- private String stringJSON = "";
- public int saveUser(User user) throws Exception{
- try{
- URL url = new URL("http://parkeasyapi.azurewebsites.net/api/Account/Register");
- HttpURLConnection connection = (HttpURLConnection)url.openConnection();
- connection.setRequestMethod("POST");
- connection.setRequestProperty("Content-Type", "application/json");
- connection.setDoOutput(true);
- OutputStream outputStream = connection.getOutputStream();
- OutputStreamWriter writer = new OutputStreamWriter(outputStream);
- connection.connect();
- writer.write(userToJson(user));
- writer.flush();
- responseCode = connection.getResponseCode();
- writer.close();
- outputStream.close();
- connection.disconnect();
- } catch (Exception e){
- e.printStackTrace();
- }
- return responseCode;
- }
- public <T>String userToJson(T user){
- Gson gson = new Gson();
- String jsonString = gson.toJson(user);
- return jsonString;
- }
- public int getToken(String email, String password) throws Exception{
- try{
- URL url = new URL("http://parkeasyapi.azurewebsites.net/token");
- HttpURLConnection connection = (HttpURLConnection)url.openConnection();
- connection.setRequestMethod("POST");
- connection.setRequestProperty("Content-Type", "x-www-form-urlencoded");
- connection.setDoOutput(true);
- OutputStream outputStream = connection.getOutputStream();
- OutputStreamWriter writer = new OutputStreamWriter(outputStream);
- connection.connect();
- writer.write("Username="+email+"&Password="+password+"&grant_type=password");
- writer.flush();
- responseCode = connection.getResponseCode();
- writer.close();
- outputStream.close();
- if(responseCode == 200) {
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- StringBuilder stringBuilder = new StringBuilder();
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- stringBuilder.append(line);
- }
- bufferedReader.close();
- stringJSON = stringBuilder.toString();
- JSONObject jsonObject = new JSONObject(stringJSON);
- TOKEN = jsonObject.getString("access_token");
- }
- connection.disconnect();
- } catch(Exception e){
- e.printStackTrace();
- }
- return responseCode;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement