Android发布到PHP

I'm new to Android and I want to work on taking data and sending it to a database through PHP, the issue I'm having is I'm unsure on what to do with the input. My goal is to have the user input a string on the android application and have it sent to a database through PHP. Here's my code:

package com.example.signals;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
private String convertStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (Exception e) {
        Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
    }
    return total.toString();
}



protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
final Button send = (Button)findViewById(R.id.send);
final EditText input = (EditText)findViewById(R.id.input);

send.setOnClickListener(new OnClickListener(){
    public void onClick(View v){    

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://example.com/script.php?var1=androidprogramming");
        try {
            HttpResponse response = httpclient.execute(httppost);
            if(response != null) {
                String line = "";
                InputStream inputstream = response.getEntity().getContent();
                line = convertStreamToString(inputstream);
                Toast.makeText(MainActivity.this, line, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Unable to complete your request", Toast.LENGTH_LONG).show();
            }
        } catch (ClientProtocolException e) {
            Toast.makeText(MainActivity.this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(MainActivity.this, "Caught IOException", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "Caught Exception", Toast.LENGTH_SHORT).show();
        }
    }
});
}}'

Thank you for any and all help!

You can get the input as a string:

input.getText().toString();

And append it to your url as a GET param

You want to create an HTTP request. Passing data via JSON is very convenient from Android: Simply pass in whatever data you need to send and have it wrapped in JSON like below. The 'text' field is returned and can be parsed from JSON as needed

private String postPullData(JSONObject json, String URL) throws JSONException { 
    HttpClient httpclient;
    int CONNECTION_TIMEOUT = 20*1000;
    int WAIT_RESPONSE_TIMEOUT = 20*1000;
    HttpPost httppost = new HttpPost(URL);

    String Error = "SCOMM Error: ";
    JSONArray postjson;
    URL url = null;


        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParameters, WAIT_RESPONSE_TIMEOUT);
        HttpConnectionParams.setTcpNoDelay(httpParameters, true);

        httpclient = new DefaultHttpClient(httpParameters);


        try {

            postjson = new JSONArray();
            postjson.put(json);

            // Post the data:
            httppost.setHeader("json", json.toString());
            httppost.getParams().setParameter("jsonpost", postjson);

            // Execute HTTP Post Request
            System.out.print(json);
            HttpResponse response = httpclient.execute(httppost);

            // for JSON:
            if (response != null)
            {
                InputStream is = response.getEntity().getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                    sb.append(line + "
");
                    }
                } catch (IOException e) {
                    Error += " IO Exception: " + e;
                    Log.d("SCOMM", Error);
                    e.printStackTrace();
                    return Error;
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {

                        Error += " closing connection: " + e;
                        Log.d("SCOMM", Error);
                        e.printStackTrace();
                        return Error;
                    }
                }

                return sb.toString();
           <snip> 
           // more error recovery stuff below

You have to append your data to the URL using GET/POST method. See this tutorial.

class SaveProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditProductActivity.this);
        pDialog.setMessage("Saving product ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Saving product
     * */
    protected String doInBackground(String... args) {

        // getting updated data from EditTexts
        String name = txtName.getText().toString();
        String price = txtPrice.getText().toString();
        String description = txtDesc.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_PID, pid));
        params.add(new BasicNameValuePair(TAG_NAME, name));
        params.add(new BasicNameValuePair(TAG_PRICE, price));
        params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));

        // sending modified data through http request
        // Notice that update product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                "POST", params);

        // check json success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully updated
                Intent i = getIntent();
                // send result code 100 to notify about product update
                setResult(100, i);
                finish();
            } else {
                // failed to update product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product uupdated
        pDialog.dismiss();
    }
}

First:you can't send data in main thread to server. Second: use HttpGet rather than HttpPost. Get user data you can input.getText.toString(). use AsynckTask for send data to server

class SendData extends AsyncTask<Void, Void, String>{
                @Override
                protected String doInBackground(Void... params) {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpGet httppost = new HttpGet("http://example.com/script.php?var1=androidprogramming");
                    try {
                        HttpResponse response = httpclient.execute(httppost);
                        if(response != null) {
                            String line = "";
                            InputStream inputstream = response.getEntity().getContent();
                            line = convertStreamToString(inputstream);
                            return line;
                        }
                    } catch (ClientProtocolException e) {
                        //toas can't use here
                    }
                    catch (IOException e) {

                    } catch (Exception e) {

                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    if(s != null){
                        //toast here!
                    }
                }
            }

usage

new SendData().execute()