0

I am trying to post my form data from android to website. I have searched around and here is the code that i usually find.

HttpClient httpclient = new DefaultHttpClient();
         HttpPost httppost = new HttpPost("http://localhost/adminp/script.php");

         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
         nameValuePairs.add(new BasicNameValuePair("id", "12345"));
         nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

         // Execute HTTP Post Request
         HttpResponse response = httpclient.execute(httppost);

however two things that are creating problem. Firstly, UrlEncodedFormEntity and execute both show errors: "Error:(94, 29) error: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown" and

"Error:(97, 52) error: unreported exception IOException; must be caught or declared to be thrown".

please guide me how to solve this issue.

second, HTTPClient etc have been deprecated since API 22, if someone knows about latest tutorial for method to post (URLConnection), please share with me, I'd be highly in debt.

Bilal Ahmad
  • 191
  • 1
  • 2
  • 17

1 Answers1

0

From Android sending post data to webservice

Call sendPostRequest(String username, String pass) method with parameters. You can call this method from the UI thread, the request will be sent from a different thread (AsyncTask is embedded).

private void sendPostRequest(String givenUsername, String givenPassword) {

    class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String paramUsername = params[0];
            String paramPassword = params[1];

            System.out.println("*** doInBackground ** paramUsername "
                + paramUsername + " paramPassword :" + paramPassword);

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(
                "http://lib-dm.process9.com/libertydm/ValidateUserHandler.ashx"); //> replace with your url

            httpPost.addHeader("Content-type",
                "application/x-www-form-urlencoded");
            BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair(
                "UserId", paramUsername);  // Make your own key value pair
            BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair(
                "Password", paramPassword);// make your own key value pair

            // You can add more parameters like above

            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            nameValuePairList.add(usernameBasicNameValuePair);
            nameValuePairList.add(passwordBasicNameValuePair);

            try {
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
                    nameValuePairList);
                httpPost.setEntity(urlEncodedFormEntity);

                try {
                    HttpResponse httpResponse = httpClient
                        .execute(httpPost);
                    InputStream inputStream = httpResponse.getEntity()
                        .getContent();
                    InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream);
                    BufferedReader bufferedReader = new BufferedReader(
                        inputStreamReader);
                    StringBuilder stringBuilder = new StringBuilder();
                    String bufferedStrChunk = null;
                    while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                        stringBuilder.append(bufferedStrChunk);
                    }

                    return stringBuilder.toString();

                    } catch (ClientProtocolException cpe) {
                        System.out
                            .println("First Exception coz of HttpResponese :"
                                + cpe);
                        cpe.printStackTrace();
                    } catch (IOException ioe) {
                        System.out
                            .println("Second Exception coz of HttpResponse :"
                                + ioe);
                        ioe.printStackTrace();
                    }

            } catch (UnsupportedEncodingException uee) {
                System.out
                    .println("An Exception given because of UrlEncodedFormEntity argument :"
                        + uee);
                uee.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }

    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
    sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}
Community
  • 1
  • 1
Oliver Hemsted
  • 571
  • 2
  • 13