【问题标题】:Android send PHP post and NetworkOnMainThreadExceptionAndroid 发送 PHP 帖子和 NetworkOnMainThreadException
【发布时间】:2016-10-19 13:40:59
【问题描述】:

您好,我有两个问题:

1 我想发送post php,例如我发送的Android:

        URL url = new URL("mysite.php");
        URLConnection con = url.openConnection();

        con.setDoOutput(true);
        PrintStream ps = new PrintStream(con.getOutputStream());

        ps.print("user=user");
        ps.print("&passw=pass");
        ps.print("&value1"="+1);
        ps.print("&value2"="+2);
        con.getInputStream();
        ps.close();

现在这是 mysite.php,我在其中接收帖子请求:

$user = $_POST['user'];
$password = $_POST['pass'];
$val1 = $_POST['value1'];
$val2 = $_POST['value2'];

$val3 = $_POST['value3'];

在java代码中我只发送了value1和value2,但是mysite.php需要三个变量value1、value2和value3,当我发送没有value3的post请求时,value3里面是什么? Value3 将包含空值对吗?

2 我尝试使用 android 发送 post 请求,我已经创建类:

public class SendPostEGet extends AsyncTask<String, Void, String>{

private HashMap<String, String> lista_eventi;

public SendPostEGet(HashMap<String, String> lista_eventi){

    this.lista_eventi = lista_eventi;

}

public void esegui(){

    doInBackground("");

}

@Override
protected String doInBackground(String... strings) {

    try{

        URL url = new URL("http://mysite.php");
        URLConnection con = url.openConnection();

        con.setDoOutput(true);
        PrintStream ps = new PrintStream(con.getOutputStream());

        ps.print("user=user");
        ps.print("&passw=passw");

        Iterator<String> it = lista_eventi.keySet().iterator();
        while (it.hasNext()){

            String key = it.next();
            if(lista_eventi.get(key).equals("true")){

                ps.print("&"+key+"="+1);

            }else{

                ps.print("&"+key+"="+0);

            }


        }


        con.getInputStream();


        ps.close();


    }catch (Exception e){

        e.printStackTrace();

    }


    return null;
}
}

但我有例外:

    android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
....
....
....

为什么我有这个异常?

【问题讨论】:

  • 来自服务器的响应是:NetworkManagementSocketTagger: untagSocket(40)

标签: php android post


【解决方案1】:

您正在手动调用 doInBackground()。所以它会抛出一个异常。调用 SendPostEGet.execute() 而不是调用 doInBackground()。

   public void esegui(){
    //doInBackground("");//remove this
    SendPostEGet.execute()//add this
  }

【讨论】:

  • 第一个问题?
  • 第二个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 2011-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
相关资源
最近更新 更多