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

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.

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

报告相同问题?