1

I want to send a POST RAW data of {"userid": "userid","pass":"1222"} as a user name and password. I have one layout consisting of username and password that will fetch as userid and password. I need help in trying this to retrofit

   // Triggers when LOGIN Button clicked
    public void checkLogin(View arg0) {

            // Initialize  AsyncLogin() class with userid and password
            new REST().execute();

    }



    public class REST extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // The Username & Password
            final EditText usr =  (EditText) findViewById(R.id.username);
            userid = (String) usr.getText().toString();
            final EditText pw =  (EditText) findViewById(R.id.password);
            password = (String) pw.getText().toString();
        }

        @Override
        protected Void doInBackground(Void... params) {
            HttpURLConnection urlConnection=null;
            String json = null;

            // -----------------------

            try {
                HttpResponse response;
                JSONObject jsonObject = new JSONObject();
                jsonObject.accumulate("username", usr);
                jsonObject.accumulate("password", password);
                json = jsonObject.toString();
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://mark.journeytech.com.ph/mobile_api/authentication.php");
                httpPost.setEntity(new StringEntity(json, "UTF-8"));
                httpPost.setHeader("Content-Type", "application/json");
                httpPost.setHeader("Accept-Encoding", "application/json");
                httpPost.setHeader("Accept-Language", "en-US");
                response = httpClient.execute(httpPost);
                String sresponse = response.getEntity().toString();
                Log.w("QueingSystem", sresponse);
                Log.w("QueingSystem", EntityUtils.toString(response.getEntity()));
            }
            catch (Exception e) {
                Log.d("InputStream", e.getLocalizedMessage());

            } finally {
// nothing to do here

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Toast.makeText(getApplicationContext(), email + " "+ password, Toast.LENGTH_SHORT).show();
            if (result != null) {
                // do something
            } else {
                // error occured
            }
        }

please any help because i searched a lot and didn't reach anything

  • check this https://code.tutsplus.com/tutorials/sending-data-with-retrofit-2-http-client-for-android--cms-27845 – Sunil P Jul 31 '17 at 07:38
  • using Asyntask you have done it or not? – Sunil P Jul 31 '17 at 07:39
  • Hi Sunil, that can be done. Pls. see https://stackoverflow.com/questions/45428585/postman-is-working-cannot-send-raw-data-on-android/45428742?noredirect=1#comment77819608_45428742 –  Aug 01 '17 at 09:53
  • check below answer which is marked as correct and do accordingly – Sunil P Aug 01 '17 at 10:37

2 Answers2

0

First: you should create your api interface

      public interface Api
     {
     @Headers({"Accept: application/json"})
     @FormUrlEncoded
     @POST("authentication.php")
     Call<Void> Login(@Field("[email]") String email,
                 @Field("[password]") String password);
     }

Second: In your activity you should call your function

    void Login(String email, final String password)
    {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://mark.journeytech.com.ph/mobile_api/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    Apiservice = retrofit.create(Api.class);
    Call<Void> call = service.Login(email, password);
    call.enqueue(new Callback<Void>()
    {
        @Override
        public void onResponse(Call<Void> call, Response<Void> response)
        {
                if (response.isSuccess())
               {

               }
                else
                {
                }
            }
        @Override
        public void onFailure(Call<Void> call, Throwable t)
        {
        }
    });
}
Mina Farid
  • 5,041
  • 4
  • 39
  • 46
  • Hi Mina, what is Apiservice and should I be deleting my Asynctask? Also, I put BASE_URL = "http://mark.journeytech.com.ph". pls. be guided. Thank.s –  Jul 31 '17 at 08:42
  • yes donot use your asyncTask . and the BASE_URL = http://mark.journeytech.com.ph/mobile_api/ and in your api interface put your_api_name=authentication.php . i will edit my answer – Mina Farid Jul 31 '17 at 09:17
  • Hi Mina, thank you for that comment. Btw, what's inside Apiservice? –  Jul 31 '17 at 09:20
  • you will create an interface and put the code inside it as described – Mina Farid Jul 31 '17 at 09:22
  • Hi mina, can you provide complete workable solution? I am still lost in using retrofit in posting raw data.. Thanks –  Jul 31 '17 at 09:35
0

You need to follow following steps :

  1. Network API interface
 public interface NetworkAPI {
    @GET("authentication.php")
    @Headers({"Content-Type:application/json; charset=UTF-8"})
    Call<JsonElement> loginRequest(@Body LoginRequest body);
}
  1. Login Request model class
public class LoginRequest {
    String userid;
    String password;
    public LoginRequest(String userid, String password) {
        this. userid = userid;
        this. pass = pass;
    }
}
  1. Retrofit call in your activity

String baseUrl ="http://mark.journeytech.com.ph/mobile_api/";

NetworkAPI networkAPI;

   public void loginRequest(){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    networkAPI = retrofit.create(NetworkAPI.class);

    LoginRequest loginRequest = new LoginRequest(yourusername,yourpassword);

    Call<JsonElement> call = networkAPI.loginRequest(loginRequest);

    call.enqueue(new Callback<JsonElement>() {
        @Override
        public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
            // success response

        }

        @Override
        public void onFailure(Call<JsonElement> call, Throwable t) {
           // failure response
        }
    });
}
Dory
  • 7,462
  • 7
  • 33
  • 55
  • Hi Dory, thank you for that wonderful comment. However when I put correct credentials like username:ssrci and password:1222. I don't get this `{ "status": "Log in Success!", "ucsi_num": "MARK12302010035824", "client_table": "CRM_ACTIVE", "markutype": 3 }` –  Aug 01 '17 at 02:52
  • share your gradle for retrofit. – Dory Aug 01 '17 at 04:49