httpclient方法使android无法工作



当我试图从android应用程序调用php函数(方法get)时,遇到了一些问题。应用程序中的代码是:

 try {
        String link="http://localhost?name=" + name;
        System.out.println(link);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(link);
        HttpResponse response = httpclient.execute(httpget);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {                    
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        Log.v("My Response :: ", result);

  }catch(Exception e){
     Log.i("error", ("Exception: " + e.getMessage()));
  }

在服务器端,php代码为:

  <?php
  $con=mysqli_connect("localhost","root","","emergency");
  if (mysqli_connect_errno($con))
  {
     echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  $name = $_GET['name'];

   $sql = "INSERT INTO data (name, age, cell, sex, status, ocupation, origin, residence, contactName, phone1, phone2, latitude, longitude) values ('".$name."',23,'22256602','true','soltero','empleado','mexicano','puebla','Marua','552786','','19.038306','-98.20621')";
   echo $sql . "</br></br></br>";
   if (!mysqli_query($con,$sql))
   {
      die('Error: ' . mysqli_error($con));
   }
   echo "1 record added";
   mysqli_close($con);
   ?>

问题是我尝试了不同的方法,但仍然返回了一个null异常。。我能做什么?:It’他非常感谢你!!

localhost指向您的本地android设备。如果你想连接你的电脑,设置它的IP地址而不是localhost,例如http://192.168.1.1?name=

您不应该从UI线程建立网络连接。这就是为什么你得到了例外:

 Exception: android.os.NetworkOnMainThreadException

您应该将连接到服务器的代码移动到后台线程中,例如使用AsyncTask。

应该异步执行此操作的主要原因之一是为了避免冻结UI。

最新更新