我在android的java类中使用了以下代码。一切正常,但它不会发送任何请求。答案总是空的。
public class WebviewActivity extends Activity {
/** Called when the activity is first created. */
EditText et; Editable ur;
TextView tx;HttpResponse response;String x;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tx=(TextView)findViewById(R.id.textView1);
et=(EditText)findViewById(R.id.editText1);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(send);
}
private OnClickListener send = new OnClickListener() {
public void onClick(View v) {
ur=et.getText();
postData();
tx.setText("ans:"+x);
}};
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/name.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("name", ur.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
Log.d("myapp", "response " + response.getEntity());
x= EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} }
在php中我使用了以下代码
<?php
$name=$_POST["name"];
echo $name;
?>
知道它是如何运作的吗?
答案 0 :(得分:0)
您必须在模拟器上为localhost使用IP地址10.0.2.2。