简体   繁体   中英

Sending Parameter using POST method in Android

I want to send a parameter using POST method to server.

I'm using a ServiceHandler.java file to process the request

public class ServiceHandler {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public ServiceHandler() {

    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
                                  List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);

                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;

    }
}

And I'm passing the parameters from my Activity file

// BACKGROUND EXECUTION STARTS
        @Override
        protected Void doInBackground(Void... arg0) {


            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

           List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("pkey", "pvalue"));
            sh.makeServiceCall(url, ServiceHandler.POST, params);


            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);

            Log.d("Response: ", "> " + jsonStr);

I'm able to connect to my server but it is not receiving any parameters from my application.

Can someone modify it and send the working code Thank You

try and use this code:

ServiceHandler sh = new ServiceHandler();
List<NameValuePair> params = new ArrayList<NameValuePair>();

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();


    params.add(new BasicNameValuePair("pkey", "pvalue"));

}

@Override
protected String doInBackground(String... param) {
        // TODO Auto-generated method stub
        String json;
        try {
            json = sh.makeServiceCall(url, ServiceHandler.POST, params);

            Log.d("Response: ", "> " + json);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);


    }

You should you HttpUrlConnection instead :

public class MessageSender {
    private int responseCode;


    public boolean sendPost(YourParameter param) {

        HttpURLConnection connection;
        try {
            URL gcmAPI = new URL("your api url");
            connection = (HttpURLConnection) gcmAPI.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
                          connection.setDoOutput(true);

            ObjectMapper mapper = new ObjectMapper();
            mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
            DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());

            mapper.writeValue(dataOutputStream, param);

            dataOutputStream.flush();
            dataOutputStream.close();

            responseCode = connection.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (responseCode == 200) {
            Log.i("Request Status", "This is success response status from server: " + responseCode);
            return true;
        } else {
            Log.i("Request Status", "This is failure response status from server: " + responseCode);
            return false;
        }
    }
}

In your activity:

MessageSender mgsSender = new MessageSender();
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... params) {

                            mgsSender.sendPost(mgsContent);

                            }
                            return null;
                        }
                    }.execute();

/* Change this line on your service handler class*/

public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
if(method == "POST"){
}else if(method == "GET"){
}
}

/* On ur activity class in doinbackground*/

sh.makeServiceCall(url,"POST", params);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM