Mwas
Mwas

Reputation: 153

How to send data to a PHP script without BasicNameValuePair in Android development

I am learning Android using some online tutorials. All my java classes are good except for this one.

@Override
        protected Void doInBackground(Void... params) {
            ArrayList<NameValuePair> dataToSend = new ArrayList<>();
            dataToSend.add(new BasicNameValuePair("email", user.userEmail));
            dataToSend.add(new BasicNameValuePair("fname", user.firstName));
            dataToSend.add(new BasicNameValuePair("lname", user.lastName));
            dataToSend.add(new BasicNameValuePair("password", user.password));

            HttpParams httpRequestParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

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

            try{
                post.setEntity(new UrlEncodedFormaEntity(dataToSend));
                client.execute(post);
            }catch (Exception e){
                e.printStackTrace();

            }
            return null;
        }

Here are all the imports

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import java.util.ArrayList;

Screenshot of the error parts

I have searched other questions related to this one but I would really want answer that is specifically for my case. Please advise.

Upvotes: 0

Views: 79

Answers (4)

Naveen Tamrakar
Naveen Tamrakar

Reputation: 3339

Httpclient is Deprecated Use HttpsURLConnection

try to use volley in Android to send Data over the Network

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", "Androidhive");
                params.put("email", "[email protected]");
                params.put("password", "password123");

                return params;
            }

        };

Android Volley Example

Upvotes: 1

abdul khan
abdul khan

Reputation: 863

Create A new Class. i.e RestClient.java

public class RestClient {


    private static String SERVICE_URL;

    private ArrayList<NameValuePair> params;
    private ArrayList <NameValuePair> headers;

    private int responseCode;
    private String message;

    private String response;

    public String getResponse() {
        return response;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public RestClient(String serviceMethod)
    {
        SERVICE_URL = serviceMethod;
        //this.serviceMethod = serviceMethod;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    public String Execute(RequestMethod method) throws Exception
    {
        switch(method) {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if(!params.isEmpty()){
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }

                //SERVICE_URL +=serviceMethod;
                HttpGet request = new HttpGet(SERVICE_URL + combinedParams);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                executeRequest(request, SERVICE_URL);
                break;
            }
            case POST:
            {
                //SERVICE_URL +=serviceMethod;
                HttpPost request = new HttpPost(SERVICE_URL);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                if(!params.isEmpty()){
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                }

                executeRequest(request, SERVICE_URL);
                break;
            }
        }
        return response;
    }

    private String executeRequest(HttpUriRequest request, String url)
    {
        HttpClient client = new DefaultHttpClient();

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }
            SERVICE_URL+=SERVICE_URL;
        } catch (ClientProtocolException e)  {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }

        return response;
    }

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }}

now in you AsyncTask you can call your Web services, that can be Post, Get etc. You can also easily add Header

example:

@Override
    protected Void doInBackground(Void... voids) {

        try {

            RestClient client = new RestClient("your url goes here");
            client.AddParam("param1", "value1"));
            client.AddParam("param2", "value2"));
            client.AddHeader("Headername","Value");
            client.Execute(RequestMethod.POST);
            response = client.getResponse();

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

For GET method just replace "client.Execute(RequestMethod.POST)" with "client.Execute(RequestMethod.GET)"

Upvotes: 1

ikhsanudinhakim
ikhsanudinhakim

Reputation: 1634

You should use most popular network library like retrofit or volley instead of using android HttpClient deprecated method. Retrofit is pretty simple to use. You can start it from here:

http://square.github.io/retrofit/

https://inthecheesefactory.com/blog/retrofit-2.0/en

Upvotes: 1

SaravInfern
SaravInfern

Reputation: 3388

Httpclient is deprecated in the latest versions of android sdk use volley instead, refer here

https://developer.android.com/training/volley/simple.html

Upvotes: 1

Related Questions