HttpURLConnection发送POST数据会产生错误

时间:2013-07-12 17:11:29

标签: java android httpurlconnection

我正在使用this脚本尝试将POST数据从我的Android应用程序发送到PHP脚本。但它甚至没有让我运行它由于错误“loginUrl无法解决”。由于其他人似乎已经使用此代码,我是否错过了一些明显的东西?这是代码,但由我改变(通过上面链接的评论看到它):

    public void postData() {
    URL url;
    HttpURLConnection conn;

    try{
    url=new URL("http://mysite/test.php");

    String param="param1=" + URLEncoder.encode("value1","UTF-8")+
    "&param2="+URLEncoder.encode("value2","UTF-8")+
    "&param3="+URLEncoder.encode("value3","UTF-8");

    conn=(HttpURLConnection)loginUrl.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");

    conn.setFixedLengthStreamingMode(param.getBytes().length);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    PrintWriter out = new PrintWriter(conn.getOutputStream());
    out.print(param);
    out.close();

    String response= "";

    Scanner inStream = new Scanner(conn.getInputStream());

    while(inStream.hasNextLine())
    response+=(inStream.nextLine());

    }
    catch(MalformedURLException ex){  
    Toast.makeText(GameButton.this, ex.toString(), 1 ).show();

    }
    catch(IOException ex){

    Toast.makeText(GameButton.this, ex.toString(), 1 ).show();
    }
} 

谢谢!

1 个答案:

答案 0 :(得分:2)

您已将变量声明为url,但您尝试将其用作loginUrl

在代码中检查这些声明和启动

    URL url;
    url=new URL("http://mysite/test.php");
当您尝试打开连接时

和问题:

conn=(HttpURLConnection)loginUrl.openConnection();

应该是

conn=(HttpURLConnection)url.openConnection();