我在this site的帮助下编写了以下代码。但是因为我在我的设备中使用了PHPRunner
。我按如下方式更改了url
:
http://127.0.0.1:8080/apps/connection.php
但是当我点击按钮显示来自php server
的输入时,输入将不会从php
文件显示到Android屏幕。
public class MainActivity extends Activity {
TextView content;
EditText fname, email, login, pass;
String Name, Email, Login, Pass;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = (TextView)findViewById( R.id.content );
fname = (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
login = (EditText)findViewById(R.id.loginname);
pass = (EditText)findViewById(R.id.password);
Button saveme=(Button)findViewById(R.id.save);
saveme.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
try{
// CALL GetText method to make post method call
GetText();
}
catch(Exception ex)
{
content.setText(" url exeption! " );
}
}
});
}
// Create GetText Metod
public void GetText() throws UnsupportedEncodingException
{
// Get user defined values
Name = fname.getText().toString();
Email = email.getText().toString();
Login = login.getText().toString();
Pass = pass.getText().toString();
// Create data variable for sent values to server
String data = URLEncoder.encode("name", "UTF-8")
+ "=" + URLEncoder.encode(Name, "UTF-8");
data += "&" + URLEncoder.encode("email", "UTF-8") + "="
+ URLEncoder.encode(Email, "UTF-8");
data += "&" + URLEncoder.encode("user", "UTF-8")
+ "=" + URLEncoder.encode(Login, "UTF-8");
data += "&" + URLEncoder.encode("pass", "UTF-8")
+ "=" + URLEncoder.encode(Pass, "UTF-8");
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://127.0.0.1:8080/apps/connection.php");
// Send POST data request
URLConnection conn = url.openConnection();
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 + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response on activity
content.setText( text );
}
和
<?php
$name = urldecode($_POST['name']);
$user = urldecode($_POST['user']);
$email = urldecode($_POST['email']);
$pass = urldecode($_POST['pass']);
print " ==== POST DATA =====
Name : $name
Email : $email
User : $user
Pass : $pass";
?>