0

I was trying to send like : Here's the raw data that I am using in postman's that is working however, I don't know what is the problem

{"userid": "ssrci","pass":"1222"}

I am guessing it was sending a plain text instead of json formatted text. I am not getting the result I want to receive once I send the data

Here's my code

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // get reference to the views
        userId = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        btnPost = (Button) findViewById(R.id.loginButton);


        // add click listener to Button "POST"
        btnPost.setOnClickListener(this);


    }

    public static String POST(String url, Account account) {
        InputStream inputStream = null;
        String result = "";
        try {

            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);

            String json = "";


            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("userid", account.getUserid());
            jsonObject.accumulate("password", account.getPassword());

            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();


            // 10. convert inputstream to string
            if (inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        // 11. return result
        return result;
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.loginButton:
                if (!validate())
                    Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
                // call AsynTask to perform network operation on separate thread
                new HttpAsyncTask().execute("http://mark.journeytech.com.ph/mobile_api/authentication.php");
                break;
        }

    }

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {
                account = new Account();
                account.setUserid(userId.getText().toString());
                account.setPassword(password.getText().toString());

                return POST(urls[0], account);
            }

            // onPostExecute displays the results of the AsyncTask.
            @Override
            protected void onPostExecute(String result) {
                Toast.makeText(getBaseContext(), "Data Sent!" + result, Toast.LENGTH_LONG).show();
            }
        }


}

Here's the account

class Account {

    private String userid;
    private String password;

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "[userid=" + userid + ", pass=" + password + "]";
    }

There's something I missed that needs reconfiguration?? Could you please help me with some code solution ? Thanks

  • 3
    You need to specify what error(s) you're getting, etc. Your question is too broad. – Difster Aug 01 '17 at 03:47
  • Hi Difster, I am having this error `Error:(79, 65) error: incompatible types: ContentType cannot be converted to String` at StringEntity se = new StringEntity(json, ContentType.APPLICATION_JSON); –  Aug 01 '17 at 04:32

2 Answers2

0

You are missing the ContentType when creating your StringEntity (so it is defaulting to TEXT_PLAIN, but you probably want to use APPLICATION_JSON)

In your code, change:

StringEntity se = new StringEntity(json);

for:

StringEntity se = new StringEntity(json, ContentType.APPLICATION_JSON);

spuente
  • 314
  • 5
  • 16
  • Hi spuente, I am having this error `Error:(79, 65) error: incompatible types: ContentType cannot be converted to String` –  Aug 01 '17 at 04:24
  • I was using http://loopj.com/android-async-http/ version `1.4.9`, which includes an *httpclient* library. If you can't resolve ContentType. APPLICATION_JSON then you're probably using Apache's http directly. You probably want to update your code, since Apache http is no longer included in Android 6 and above. See this question's old and new answer for further info https://stackoverflow.com/a/2938787/3189164. Hope this helps – spuente Aug 01 '17 at 05:06
0

username and password is case sensitive, just set this

 JSONObject jsonObject = new JSONObject();
                jsonObject.accumulate("userid", account.getUserid());
                jsonObject.accumulate("pass", account.getPassword());

like

{"userid": "ssrci","pass":"1222"}

and use above code.