
[英]Server cannot get binary data from Android app when using HttpPost
[英]Using HttpPost to get data from local server
我在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;
?>
知道它是如何工作的吗?
您必须在仿真器上将IP地址10.0.2.2用于本地主机。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.