2015-07-19 81 views

回答

0

Yes.Check這個例子:How To Post Data From An Android App To a Website

MainActivity:

public class HelloWorldActivity extends Activity { 
    Button sendButton;  
    EditText msgTextField; 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     // load the layout 
     setContentView(R.layout.main);   

     // make message text field object 
     msgTextField = (EditText) findViewById(R.id.msgTextField); 
     // make send button object 
     sendButton = (Button) findViewById(R.id.sendButton); 

    } 

    // this is the function that gets called when you click the button 
    public void send(View v) 
    { 
     // get the message from the message text box 
     String msg = msgTextField.getText().toString(); 

     // make sure the fields are not empty 
     if (msg.length()>0) 
     { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://yourwebsite.com/yourPhpScript.php"); 
     try { 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
      nameValuePairs.add(new BasicNameValuePair("message", msg)); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      httpclient.execute(httppost); 
      msgTextField.setText(""); // clear text box 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 

     } 
     else 
     { 
      // display message if text fields are empty 
      Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); 
     } 

    } 

} 

服務器端代碼:

<?php 
// get the "message" variable from the post request 
// this is the data coming from the Android app 
$message=$_POST["message"]; 
// specify the file where we will save the contents of the variable message 
$filename="androidmessages.html"; 
// write (append) the data to the file 
file_put_contents($filename,$message."<br />",FILE_APPEND); 
// load the contents of the file to a variable 
$androidmessages=file_get_contents($filename); 
// display the contents of the variable (which has the contents of the file) 
echo $androidmessages; 
?> 
+0

感謝您的答覆,只是想知道會的工作爲任何網站?我的意思是如果我沒有直接鏈接到服務器。 – HunterrJ

+0

我不確定它是否適用於任何網站,因爲它使用'PHP'代碼,我對'Php'沒有任何意見。但是這是一個使用'POST'發送的例子,你應該測試它並學習如何處理這個php。 – Mohsen

+0

也有一些接口已棄用。 – HunterrJ