Android 如何将请求发送到 HTTP POST 请求到服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10431619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:43:26  来源:igfitidea点击:

How to send request to HTTP POST request to server

androidhttp-post

提问by divaNilisha

Hello I am using two buttons which on click show date picker dialog and time picker dialog. I have a spinner.

您好,我正在使用两个按钮,单击时显示日期选择器对话框和时间选择器对话框。我有一个陀螺。

I want to send the user input value to a php server. What should I do for the client side code?

我想将用户输入值发送到 php 服务器。我应该为客户端代码做什么?

Here is my code:

这是我的代码:

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;
    }

I am using mPickDate as the button which opens to a DatePickerDialog mPickTime as the button which on click opens TimePicker Dialog One Spinner (spinner1) to get the list of item. mDateDisplay to show the date which is edited by user after clicking DatePickerDialog. mTimeDisplay to show the time which is edited by user after clicking TimePickerDialog.

我使用 mPickDate 作为打开 DatePickerDialog mPickTime 作为按钮的按钮,单击该按钮打开 TimePicker Dialog One Spinner (spinner1) 以获取项目列表。mDateDisplay 显示用户在点击 DatePickerDialog 后编辑的日期。mTimeDisplay 显示用户点击 TimePickerDialog 后编辑的时间。

I want the string values of user input of DatePickerDialog,TimePickerDialog and spinner to send to server as HTTP post . Please tell me how to do ?I want the detail code.

我希望 DatePickerDialog、TimePickerDialog 和 spinner 的用户输入的字符串值作为 HTTP post 发送到服务器。请告诉我该怎么做?我想要详细代码。

采纳答案by Gaurav Agarwal

Follow the tutorials hereor hereand you may wish to go through Android Developer HTTP Post

按照此处此处的教程进行操作,您可能希望通过Android Developer HTTP Post

回答by Sebastian Breit

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
    }
} 

回答by Harsh Dev Chandel

    // 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", "[email protected]"));
        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;