【发布时间】:2014-07-23 13:50:25
【问题描述】:
我创建了一个活动来测试从我的应用程序连接到 WAMP 服务器。但是目前它似乎不起作用。
一旦连接到服务器并单击按钮,该活动应更改屏幕上的文本框。但是目前它没有改变。
下面的代码有错误吗?注意:我在 Logcat 中看不到任何错误,并且服务器日志没有显示连接。
服务器类:
public class Server {
// Declared Constants
public static final String SERVER_URL = "http://192.168.56.1/androidtest.php"; //need to change?
/**
* Gets the bit of text to set
* @return A string containing the text to set
*/
public static String getTextToSet() {
/*
* Let's construct the query string. It should be a key/value pair. In
* this case, we just need to specify the command, so no additional
* arguments are needed.
*/
String data = "command=" + URLEncoder.encode("getTextToSet");
return executeHttpRequest(data);
}
/**
* Helper function used to communicate with the server by sending/receiving
* POST commands.
* @param data String representing the command and (possibly) arguments.
* @return String response from the server.
*/
private static String executeHttpRequest(String data) {
String result = "";
try {
URL url = new URL(SERVER_URL);
URLConnection connection = url.openConnection();
/*
* We need to make sure we specify that we want to provide input and
* get output from this connection. We also want to disable caching,
* so that we get the most up-to-date result. And, we need to
* specify the correct content type for our data.
*/
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//connection.setRequestProperty("Content -Type", "textback.php");
//connection.setRequestProperty("Value1", "Value2");
// Send the POST data
DataOutputStream dataOut = new DataOutputStream(connection.getOutputStream());
dataOut.writeBytes(data);
dataOut.flush();
dataOut.close();
// get the response from the server and store it in result
DataInputStream dataIn = new DataInputStream(connection.getInputStream());
String inputLine;
while ((inputLine = dataIn.readLine()) != null) {
result += inputLine;
}
dataIn.close();
} catch (IOException e) {
/*
* In case of an error, we're going to return a null String. This
* can be changed to a specific error message format if the client
* wants to do some error handling. For our simple app, we're just
* going to use the null to communicate a general error in
* retrieving the data.
*/
e.printStackTrace();
result = null;
}
return result;
}
}
连接到服务器类:
public class ConnectToServer extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connecttoserver);
final String textToSetAs = null;
TextView tv = (TextView) findViewById(R.id.text_to_set);
// Call the task to set the text on screen
Button setText = (Button) findViewById(R.id.button_to_set_text);
setText.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
(new GetTextTask()).execute();
}
});
}
/**
// * Used to spawn a thread to retrieve the animal sound?
*/
@SuppressWarnings("unchecked")
private class GetTextTask extends AsyncTask {
/**
* Let's make the http request and return the result as a String.
*/
protected String doInBackground(Object... args) {
// Return the server call to get the text to set
return Server.getTextToSet();
}
/**
* Display the result as a Toast.
*/
protected void onPostExecute(Object objResult) {
// check to make sure we're dealing with a string
/*
* if (objResult != null && objResult instanceof String) { String
* result = (String) objResult;
* Toast.makeText(getApplicationContext(), result,
* Toast.LENGTH_SHORT).show(); }
*/
TextView tv = (TextView) findViewById(R.id.text_to_set);
tv.setText((CharSequence) objResult);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
PHP 脚本:
<?php
echo "Did it work?";
// get the command
$command = $_REQUEST['command'];
// determine which command will be run
if($command == "getTextToSet") {
// return the text to set
echo "This is what you wanted back?";
} else {
echo "";
}
?>
【问题讨论】:
-
您为什么不尝试使用调试器或简单地使用
Log.d(..)进行调试?检查 AsyncTaskdoInBackground是否到达,然后检查结果是否返回到onPostExecute。在executeHttpRequest中检查来自服务器的确切响应。另外,检查 IP 是否正确,以及您的设备是否连接到正确的 wi-fi。对于模拟器,你可以试试localhost,虽然没有保证。 -
您是否尝试将您的网址粘贴到浏览器中以测试连接?
-
是的,我可以使用 PHP 脚本填充 MySQL 数据库,但我似乎无法与 Android 应用程序建立任何连接!?
-
我相信你是说你可以在你的服务器上运行一个PHP脚本并得到一个正确的结果。这并不意味着您的网址是正确的。一个简单的测试是将 URL 粘贴到浏览器的地址栏中。您应该看到“它有效吗?”如果不是,则 URL 不正确。
-
是的,每当我在浏览器中运行 PHP 脚本时,我都会看到“它工作正常”的消息,这是否意味着错误与 android 应用程序有关?对此问题的任何帮助将不胜感激!