0
           in = new DataInputStream(conn.getInputStream());
            String str = "";
            while (in.available() > 0) {
                str += in.readUTF();
            }

           in = new DataInputStream(conn.getInputStream());
            String str = "";
            while (in.available() > 0) {
                str2 += Bytes.toString(in.readBytes());
            }

I cannot read any response from my php page with two methods above.

           in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String str2="";
                while ( (str  += in.readLine()) != null && in.ready()){} 

And only this method can works.

Can someone tell me what it is happening either there's the problem of inputstream ,type or charset. Thanks!!

  • Are you sure you want to use DataInputStream? That's a very specific binary format. You can use InputStreamReader to read text, or InputStream to read raw bytes. – Thilo Feb 27 '16 at 08:03
  • `in.available()` is also probably not something you should check. That will return false if the server response is not in yet. Just read without the check. It will block until enough data is available. – Thilo Feb 27 '16 at 08:05
  • Is that mean datainputstream does not suitable for reading text over http? thanks! – TanakaSakana Feb 27 '16 at 08:12
  • Take a look at http://stackoverflow.com/questions/29058727/i-need-an-option-to-httpclient-in-android-to-send-data-to-php-as-it-is-deprecate/29060004#29060004 – fateddy Feb 27 '16 at 09:29

1 Answers1

1

readUTF() can only read data that was written by writeUTF(). Unless you know that the server is sending data in that format you should not use it. It isn't a general-purpose string-reading method.

Possibly you're looking for BufferedReader.readLine(), but without knowing your application payload protocol it is impossible to be sure.

while ( (str  += in.readLine()) != null && in.ready()){}

+= is the wrong operation here. It makes it impossible for the following null test to ever be true. Use =, and append inside the loop. The ready() test is futile here too. What you're testing here is (a) a line was returned and (b) some further data is pending ready to be read without blocking. You don't care about (b). Remove that. You probably meant to write the tests in the opposite order, but it would still be futile. Just block in readLine(). Set a read timeout if you don't entirely trust the server.

user207421
  • 305,947
  • 44
  • 307
  • 483