Good day, programmers, just recently started learning how to develop mobile apps for Android, and encountered such a problem; you need to implement registration and authorization in your application using Post requests. As I understand the registration (login) is performed using the post request for the corresponding endpoints, the request body should be passed json, for example:

{"username": "user1", "password": "1234"}

After registration (login) returns a token or error message.

As I have little experience, I don’t know how to implement the text fields for entering the login password to be converted to json format, and sent by post to the corresponding api / register (login).

Maybe someone has an example of the implementation of a similar task or an Internet source where you can learn some material for the implementation of this task.

Made a form to enter a login and password.

public class LoginActivity extends AppCompatActivity { private EditText emailText; private EditText passwordText; private Button loginBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login1); initComponent(); loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ((!emailText.getText().toString().equals("")) && (!passwordText.getText().toString().equals(""))) { } else if ((!emailText.getText().toString().equals(""))) { Toast.makeText(getApplicationContext(), "Password field empty", Toast.LENGTH_SHORT).show(); } else if ((!emailText.getText().toString().equals(""))) { Toast.makeText(getApplicationContext(), "Login name field empty", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Login name and Password field are empty", Toast.LENGTH_SHORT).show(); } } }); } private void initComponent() { emailText = (EditText) findViewById(R.id.input_email); passwordText = (EditText) findViewById(R.id.input_password); loginBtn = (Button) findViewById(R.id.btn_login); } } 

I wrote a POST request using your example for registration, but it does not create an account at http://smktesting.herokuapp.com/api/register/ .

  public class PostReg { private static final String TAG ="mee"; public static String doPost(String url, String jsonString) throws Exception { final String login = "yxz"; final String password ="test"; //jsonString = object.toString(); URL obj = new URL("http://smktesting.herokuapp.com/api/register/"); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); //add reuqest header connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); connection.setRequestProperty("Content-Type", "text/plain"); connection.setReadTimeout(15000); connection.setConnectTimeout(15000); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); JSONObject jsonParam = new JSONObject(); jsonParam.put("usernam", login); jsonParam.put("password", password); Uri.Builder builder = new Uri.Builder() .appendQueryParameter("username", login) .appendQueryParameter("password", password); String urlParameters = builder.build().getEncodedQuery(); OutputStream dStream = new BufferedOutputStream(connection.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(dStream, "utf-8")); //Send request //DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); //outputStream.writeBytes(jsonString); writer.write(urlParameters); writer.flush(); writer.close(); int responseCode = connection.getResponseCode(); Log.d(TAG,"\n-----------Send http request-----------"); Log.d(TAG, "\nSending request to URL : " + url); Log.d(TAG, "Post parameters : " + jsonString); Log.d(TAG, "Response Code : " + responseCode); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = bufferedReader.readLine()) != null) { response.append(inputLine); } bufferedReader.close(); // print result Log.d(TAG,"Response string: " + response.toString()); Log.d(TAG,"-----------end http request-----------\n"); Log.d(TAG, " "); return response.toString(); } } 

    2 answers 2

    I figured it out myself, below is the registration implementation work code:

      public class RegisterActivity extends AppCompatActivity { Context c; EditText regLogin; EditText passwordText; Button regloginBtn; String password; String rLogin; String url = "http://smktesting.herokuapp.com/api/register/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); c = this; regLogin = (EditText) findViewById(R.id.input_login_register); passwordText = (EditText) findViewById(R.id.input_password_register); regloginBtn = (Button) findViewById(R.id.btn_register); regloginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // _("Login button hit"); rLogin = regLogin.getText() + ""; password = passwordText.getText() + ""; if ( rLogin.length() == 0 || password.length() == 0) { Toast.makeText(c, "Please fill in all fields", Toast.LENGTH_SHORT).show(); return; } if ( rLogin.length() > 0 && password.length() > 0) { //Do networking Networking n = new Networking(); n.execute(url, Networking.NETWORK_STATE_REGISTER); Toast.makeText(c, "Register Done", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegisterActivity.this, MainActivity.class); startActivity(intent); } } }); } //AsyncTask good for long running tasks public class Networking extends AsyncTask { public static final int NETWORK_STATE_REGISTER = 1; @Override protected Object doInBackground(Object[] params) { getJson((String) params[0], (Integer) params[1]); return null; } } private void getJson(String url, int state) { //Do a HTTP POST, more secure than GET HttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(url); List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); boolean valid = false; switch (state) { case Networking.NETWORK_STATE_REGISTER: //Building key value pairs to be accessed on web postParameters.add(new BasicNameValuePair("username", rLogin)); postParameters.add(new BasicNameValuePair("password", password)); valid = true; break; default: Toast.makeText(c, "Unknown state", Toast.LENGTH_SHORT).show(); } if (valid == true) { //Reads everything that comes from server BufferedReader bufferedReader = null; StringBuffer stringBuffer = new StringBuffer(""); try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters); request.setEntity(entity); //Send off to server HttpResponse response = httpClient.execute(request); //Reads response and gets content bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; String LineSeparator = System.getProperty("line.separator"); //Read back server output while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line + LineSeparator); } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } decodeResultIntoJson(stringBuffer.toString()); } else { } } private void decodeResultIntoJson(String response) { if (response.contains("error")) { try { JSONObject jo = new JSONObject(response); String error = jo.getString("error"); } catch (JSONException e) { e.printStackTrace(); } } try { JSONObject jo = new JSONObject(response); String success = jo.getString("success"); String message = jo.getString("message"); } catch (JSONException e) { e.printStackTrace(); } } 

    }

      Here is an example POST request:

       public static String doPost(String url, String jsonString) throws Exception { URL obj = new URL(url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); //add reuqest header connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", Mozilla/5.0"); connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); connection.setRequestProperty("Content-Type", "text/plain"); //Send request connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(jsonString); outputStream.flush(); outputStream.close(); int responseCode = connection.getResponseCode(); Log.d(TAG,"\n-----------Send http request-----------"); Log.d(TAG, "\nSending request to URL : " + url); Log.d(TAG, "Post parameters : " + jsonString); Log.d(TAG, "Response Code : " + responseCode); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = bufferedReader.readLine()) != null) { response.append(inputLine); } bufferedReader.close(); // print result Log.d(TAG,"Response string: " + response.toString()); Log.d(TAG,"-----------end http request-----------\n"); Log.d(TAG, " "); return response.toString(); } 

      Json string can be done like this:

       JSONObject object = new JSONObject(); object.put("login", yourLogin); object.put("password", yourPassword); String jsonString = object.toString();