dounouxi1020 2014-09-22 11:28
浏览 87
已采纳

Android getInputStream.ReadBoolean问题

I'm doing an SQL-query from a PHP-script, that echo's 1 if succesful and 0 if not. This is just echo'ed in the body.

To send the information i wanna query in the database, I'm using this: (This is an Android project, using AsyncTask and the issue is in the 'new' thread, created with doInBackground)

        protected Boolean doInBackground(String... params) {
        try {
        String request = "PHP-file-location";
        URL url = new URL(request); 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false); 
        connection.setRequestMethod("POST"); 
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setUseCaches (false);

        DataOutputStream os = new DataOutputStream(connection.getOutputStream());
        os.writeBytes(urlParameters);
        os.flush();
        os.close();
        ... continues.

The PHP-script handles the information (this part works - checked with .html form) and echo's the 0 or 1, that I now wanna pick up in my Android-application:

DataInputStream is = new DataInputStream(connection.getInputStream());
        boolean response = is.readBoolean();
        is.close();
        connection.disconnect();

        if(is!=null)
            is.close();
        if(os!=null)
            os.close();
        return response;

But for some reason it says the value is true, both if 0 or 1. Am i using readBoolean wrong? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • doujun1495 2014-09-22 12:39
    关注

    Wrong. The response is a plain text... You should be using something like this:

    reader = new InputStreamReader (connection.getInputStream());
            int c = reader.read();
            if (c == '0') {
    
            } else if (c == '1') {
    
            }
    

    remember closing the stream after done.

    I dont understand very well what you´re doing with the body and the url parameters... Anyway. DataOutput and DataInput streams are for writing and reading binary serializations of objects, don´t play too much with them if you want your interfaces to be compatible with other clients/programming languages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行