Hi i have two question:
1 I want send post php, for example with Android i send:
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();
Now this is mysite.php where i reiceive post request:
$user = $_POST['user'];
$password = $_POST['pass'];
$val1 = $_POST['value1'];
$val2 = $_POST['value2'];
$val3 = $_POST['value3'];
In the java code i have only send value1 and value2, but mysite.php requires three variables value1, value2 and value3, when i will send post request without value3, in value3 what's inside? Value3 will contain null value right?
2 I have try to send post request with android, i have create class:
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;
}
}
But i have exception:
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)
....
....
....
Why i have this exception?
答案 0 :(得分:0)
您手动调用doInBackground()。所以它会抛出异常。调用SendPostEGet.execute()而不是调用doInBackground()。
public void esegui(){
//doInBackground("");//remove this
SendPostEGet.execute()//add this
}