如何向服务器发送HTTP POST请求

6

你好,我正在使用两个按钮,点击后会弹出日期选择器和时间选择器。 我还有一个下拉菜单。

我想将用户输入的值发送到PHP服务器。 客户端代码应该怎么做呢?

以下是我的代码:

public class DineOutActivity extends Activity {

    private TextView mDateDisplay;
    private Button mPickDate;
    private int mYear;
    private int mMonth;
    private int mDay;
   /******************time picker**************/
        private TextView mTimeDisplay;
           private Button mPickTime;
           private int mHour;
           private int mMinute;
           private int mAmPm;

           static final int TIME_DIALOG_ID=1;

        static final int DATE_DIALOG_ID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /********************spinner***********/

        Spinner food = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence> foodadapter = ArrayAdapter.createFromResource(
                    this, R.array.item_array, android.R.layout.simple_spinner_item);
        foodadapter.setDropDownViewResource(R.layout.spinner_layout);
        food.setAdapter(foodadapter);
        /**pick date*/

        mDateDisplay = (TextView) findViewById(R.id.textView2);
        mTimeDisplay = (TextView) findViewById(R.id.textView4);
        mPickDate = (Button) findViewById(R.id.button2);
       /**pick time**/

        mPickTime=(Button)findViewById(R.id.button3);

        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() {

                     public void onClick(View v) {

                           showDialog(TIME_DIALOG_ID);
                     }
              });

        // get the current time
        final Calendar c=Calendar.getInstance();
        mHour=c.get(Calendar.HOUR_OF_DAY);
        mMinute=c.get(Calendar.MINUTE);
        mAmPm = c.get(Calendar.AM_PM);

        // display the current date
       upTimeDisplay();


/*****************************pick date***********************************/
        // add a click listener to the button
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v1) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        // get the current date
        final Calendar date = Calendar.getInstance();
        mYear = date.get(Calendar.YEAR);
        mMonth = date.get(Calendar.MONTH);
        mDay = date.get(Calendar.DAY_OF_MONTH);
        int mDst = date.get(Calendar.AM_PM);
        int mAmPm = date.get(Calendar.DST_OFFSET);

        // display the current date (this method is below)
        updateDisplay();
    }

    // updates the date in the TextView




   private void upTimeDisplay()
   {
     //  mTimeDisplay.setText(new  
           //    StringBuilder().append(pad(mHour)).append(":").append(pad(mMinute)).append(pad(mAmPm)));
       mTimeDisplay.setText(new  
                  StringBuilder().append(mHour).append(":").append(mMinute));
       mTimeDisplay.setTextColor(R.color.green);
   }
  /** private Object pad(int mMinute2) {

       if(mMinute2>=10)
              return String.valueOf(mMinute2);
       else
              return "0"+String.valueOf(mMinute2);
}**/

   private TimePickerDialog.OnTimeSetListener mtimeSetListener=new  
           TimePickerDialog.OnTimeSetListener() {

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

mHour=hourOfDay;
mMinute=minute;
int ampm;

upTimeDisplay();
}
};


    private void updateDisplay() {
        mDateDisplay.setText(new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" "));
        mDateDisplay.setTextColor(R.color.green);
                 //   .append(mHour).append("_")
                  //  .append(mMinute).append("_")));
    }

    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
                    mDay);

        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,mtimeSetListener,mHour,mMinute,false);
        }
        return null;
    }

我正在使用mPickDate作为打开DatePickerDialog的按钮,mPickTime作为单击后打开TimePickerDialog的按钮,还有一个Spinner(spinner1)以获取项目列表,mDateDisplay用于显示用户在单击DatePickerDialog后编辑的日期,mTimeDisplay用于显示用户在单击TimePickerDialog后编辑的时间。
我想要将用户输入的DatePickerDialog、TimePickerDialog和spinner的字符串值作为HTTP post发送到服务器。请告诉我如何实现?详细代码请提供。
3个回答

5
public void postData() {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("text", "blablabla"));
        nameValuePairs.add(new BasicNameValuePair("date", "yourdate"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

抱歉,但是它将从用户输入中获取NameValuePair,我是说它将如何与对话框和旋转器进行映射。 - divaNilisha
它还将在服务器中存储日期和时间,我该如何将其格式设置为“YYYY/MM/DD”或“DD/MM/YYYY”? - divaNilisha
5
你是自己写的这段代码吗?不可能,你居然问我这个问题 ¬¬ - Sebastian Breit
nameValyePairs 的用途是什么? - madhu
我想将字符串发送到MySQL,我该如何发出请求? - madhu

3
    // Create a new HttpClient and Post Header
    String downloadedString= null;

    HttpClient httpclient = new DefaultHttpClient();


    //for registerhttps://te
    HttpPost httppost = new HttpPost("url here");
    //add data
    try{
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
        nameValuePairs.add(new BasicNameValuePair("firstname", "harsh"));
        nameValuePairs.add(new BasicNameValuePair("lastname", "chandel"));
        nameValuePairs.add(new BasicNameValuePair("email", "mike.bulurt66@gmail.com"));
        nameValuePairs.add(new BasicNameValuePair("phone", "944566778"));
        nameValuePairs.add(new BasicNameValuePair("username", "mikebulurt"));
        nameValuePairs.add(new BasicNameValuePair("password", "qwert"));
        nameValuePairs.add(new BasicNameValuePair("device_duid", "986409987"));

        //add data
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

        InputStream in = response.getEntity().getContent();
        StringBuilder stringbuilder = new StringBuilder();
        BufferedReader bfrd = new BufferedReader(new InputStreamReader(in),1024);
        String line;
        while((line = bfrd.readLine()) != null)
            stringbuilder.append(line);

        downloadedString = stringbuilder.toString();

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("downloadedString:in login:::"+downloadedString);


    return downloadedString;

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接