使用HttpPost获得从本地服务器上的数据 [英] Using HttpPost to get data from local server
本文介绍了使用HttpPost获得从本地服务器上的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用下面的Java类的android code。一切正常,除了它不会发出任何请求。答案永远是零。
I used following code in java class of android. Everything works except it wont send any request. Answer is always null.
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我用下面的code
and in php i used following code
<?php
$name=$_POST["name"];
echo $name;
?>
不知道如何使它工作?
Any idea how it make it work?
推荐答案
您必须在模拟器上使用IP地址10.0.2.2本地主机。
You have to use IP address 10.0.2.2 for localhost on the emulator.
这篇关于使用HttpPost获得从本地服务器上的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文