這是我到目前爲止的代碼。通過Android應用程序連接到PHP腳本
public void postData(String toPost) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mywebsite.com/dev/reverser.php");
//This is the data to send
String MyName = toPost; //any data to send
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
}//end postData()
有人能告訴我下面的代碼有什麼問題!我已經確定只有try catch塊存在問題,而不是活動中的其他任何地方。我只是不知道它是什麼或如何糾正它。
我的PHP代碼很簡單。這是這樣的 -
//code to reverse the string
$reversed = strrev($_POST["action"]);
echo $reversed;
爲什麼不告訴我們你得到的異常是什麼。您可以使用android調試器來執行此操作。此外,將答覆打印爲吐司的方式也不正確。 – rockstar
AndroidRuntime(15110):java.lang.RuntimeException:無法啓動活動ComponentInfo {com.example.connectingtophpandreturningdata/com.example.connectingtophpandreturningdata.MainActivity}:android.os.NetworkOnMainThreadException –