Sending POST data in Android

2018-12-31 02:56发布

I'm experienced with PHP, JavaScript and a lot of other scripting languages, but I don't have a lot of experience with Java or Android.

I'm looking for a way to send POST data to a PHP script and display the result.

15条回答
栀子花@的思念
2楼-- · 2018-12-31 02:57

You can POST an HttpRequest using WebServer class and track the response in its listener interface.

WebServer server=new WebServer(getApplicationContext());

server.setOnServerStatusListner(new WebServer.OnServerStatusListner() {
    @Override
    public void onServerResponded(String responce) {

    }

    @Override
    public void onServerRevoked() {

    }
});

Now create a DataRack to bind your data

List<DataRack> racks=new ArrayList<DataRack>();
racks.add(new DataRack("name","Simon"));
racks.add(new DataRack("age","40"));
racks.add(new DataRack("location","Canada"));

Now simply send the POST request with that rack

server.connectWithPOST(MainActivity.this,"http://sangeethnandakumar.esy.es/PROJECTS/PUBLIC_SERVICE/posttest.php",racks);

You need to include my library for this. Documentations here

查看更多
人间绝色
3楼-- · 2018-12-31 02:59

You can use URLConnection with setDoOutput(true), getOutputStream() (for sending data), and getInputStream() (for receiving). Sun has an example for exactly this.

查看更多
素衣白纱
4楼-- · 2018-12-31 03:02

Better use Apache Commons HttpClient, that is also included in android already. Have a look at Android Developer: Apache HTTP Client Package Summary for general api info.

查看更多
明月照影归
5楼-- · 2018-12-31 03:04

If you just want to append data to the Url You can do so by using HttpUrlConnection since HttpClient is now deprecated. A better way would be to use a library like-

Volley Retrofit

We can post data to the php script and fetch result and display it by using this code performed Through AsyncTask class.

    private class LongOperation  extends AsyncTask<String, Void, Void> {

    // Required initialization


    private String Content;
    private String Error = null;
    private ProgressDialog Dialog = new ProgressDialog(Login.this);
    String data ="";
    int sizeData = 0;



    protected void onPreExecute() {
        // NOTE: You can call UI Element here.

        //Start Progress Dialog (Message)

        Dialog.setMessage("Please wait..");
        Dialog.show();
        Dialog.setCancelable(false);
        Dialog.setCanceledOnTouchOutside(false);

        try{
            // Set Request parameter
            data +="&" + URLEncoder.encode("username", "UTF-8") + "="+edittext.getText();



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

    }

    // Call after onPreExecute method
    protected Void doInBackground(String... urls) {

        /************ Make Post Call To Web Server ***********/
        BufferedReader reader=null;

        // Send data
        try
        {

            // Defined URL  where to send data
            URL url = new URL(urls[0]);

            // Send POST data request

            URLConnection conn = url.openConnection();

            conn.setConnectTimeout(5000);//define connection timeout 
            conn.setReadTimeout(5000);//define read timeout
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write( data );
            wr.flush();

            // Get the server response

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;



            // Read Server Response
            while((line = reader.readLine()) != null)
            {
                // Append server response in string
                sb.append(line + " ");
            }

            // Append Server Response To Content String
            Content = sb.toString();


        }
        catch(Exception ex)
        {
            Error = ex.getMessage();
        }
        finally
        {
            try
            {

                reader.close();
            }

            catch(Exception ex) {}
        }


        return null;
    }

    protected void onPostExecute(Void unused) {
        // NOTE: You can call UI Element here.

        // Close progress dialog
        Dialog.dismiss();

        if (Error != null) {

                Toast.makeText(getApplicationContext(),"Error encountered",Toast.LENGTH_LONG).show();



        }
        else {




            try {

                JSONObject jsonRootObject = new JSONObject(Content);


                JSONObject json2 =jsonRootObject.getJSONObject("jsonkey");//pass jsonkey here


                String id =json2.optString("id").toString();//parse json to string through parameters


     //the result is stored in string id. you can display it now


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


        }

    }

}

But using libraries such as volley or retrofit is much better option because Asynctask class and HttpurlConnection is slower compared to libraries. Also the library will fetch everything and is faster as well.

查看更多
低头抚发
6楼-- · 2018-12-31 03:08

Method to post data as HTTP request,

public static InputStream callPostService(String Url,
        List<NameValuePair> data) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(Url);
    try {
        httppost.setEntity(new UrlEncodedFormEntity(data));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        return entity.getContent();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
查看更多
情到深处是孤独
7楼-- · 2018-12-31 03:08

In newer versions of Android you have to put all web I/O requests into a new thread. AsyncTask works best for small requests.

查看更多
登录 后发表回答