-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