我一直在嘗試從android發送數據到本地服務器。我在Logcat上獲得了成功發送數據的響應,但我無法在網頁上顯示它。發送數據從android到服務器(本地主機)
Android的代碼是:
package rk.android.test.test;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import cz.msebera.android.httpclient.util.EntityUtils;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.send);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DataAsyncTask().execute();
}
});
}
public class DataAsyncTask extends AsyncTask<String, String, String>
{
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected String doInBackground(String... params)
{
try {
String postUrl = "http://192.168.137.1/receiver/receiver.php";
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "Mohan"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("OP", "Response: " + responseStr);
// you can add an if statement here and do oth
}
}catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
}
PHP代碼爲:
<?php
$reversed = strrev($_POST["action"]);
echo $reversed;
?>
logcat的迴應是:
04-06 02:36:55.789 17879-17959/rk.android.test.test V/OP: Response: nahoM
問題是我得到加載一個空白頁receiver.php文件!