-1
我試圖從Android發送一個HTTP請求到下面這段代碼的PHP,但應用程序在啓動時不斷崩潰。發送來自Android的HTTP請求到PHP
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_test);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.1.5:80/arduino2/socket.php");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("lighton", ""));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
} catch (IOException e) {
e.printStackTrace();
}
}
這是我試圖發送請求的PHP(socket.php
)文件。這個PHP文件向Arduino發送一個請求,當使用HTML按鈕並提交表單時,該請求可以正常工作。
<?php
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock,"192.168.1.8", 80);
$msg = 'a';
if (isset($_POST['lighton'])){
$msg='lighton';
}
if (isset($_POST['lightoff'])){
$msg='lightoff';
}
if (isset($_POST['relayoff'])){
$msg='relayoff';
}
if (isset($_POST['relayon'])){
$msg='relayon';
}
if (isset($_POST['temp'])){
$msg='temp';
}
echo $sock;
socket_write($sock, $msg);
sleep(1);
header("Location: http://192.168.1.5/arduino2/index.php"); /* Redirect browser */
exit();
?>
你在你的UI線程使用的AsyncTask此 –
使用線程和處理程序或執行的AsyncTask網絡請求,因爲這個過程應該在後臺執行。 – Chefes