-1

I am trying to make a login and register for an android app. I have been having problems adjusting the code to API 22. Although I know I have to use HttpURLConnection instead of HttpRequestParams etc., and have done that, I can't figure out how to adjust the code to incorporate the database server and my PHP files stored on there.

It's mostly this bit below that I can't figure out.

HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");

Can anyone help? Thanks in advance.

Here's the full code:

        @Override
        protected User doInBackground(Void... params) {

            ContentValues contentValues = new ContentValues();
            contentValues.put("username", user.username);
            contentValues.put("password", user.password);

            URL url = new URL(SERVER_ADDRESS);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setReadTimeout(CONNECTION_TIMEOUT);

            HttpClient client = new DefaultHttpClient(httpRequestParams);
            HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");

            User returnedUser = null;
            try {
                post.setEntity(new UrlEncodedFormEntity(dataToSend));
                HttpResponse httpResponse = client.execute(post);

                HttpEntity entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity);
                JSONObject jObject = new JSONObject(result);

                if(jObject.length() == 0) {
                    returnedUser = null;
                } else {
                    String mobile = jObject.getString("mobile");
                    String email = jObject.getString("email");

                    returnedUser = new User(mobile, email, user.mobile, user.email);
                }

            } catch(Exception e) {
                e.printStackTrace();
            }

            return returnedUser;
        }
Prudhvi
  • 2,276
  • 7
  • 34
  • 54
costa29
  • 43
  • 3
  • 2
    If you're open to using a third party library, Retrofit greatly simplifies API requests: http://square.github.io/retrofit/ – blackcj Jun 30 '15 at 16:30

1 Answers1

1

first: It's already been answered Sending Http request for Android 22+

second: I've made a class that meets your needs, which allow you to send request and receive response with one line of code (It's also explained in post above)

Here is the link for the my class:

HttpRequest

Community
  • 1
  • 1
Nikita Kurtin
  • 5,889
  • 4
  • 44
  • 48