Share a very useful Java program (key Code) (eight)---Java InputStream read the network response response data Method! Important

Source: Internet
Author: User

Original: Share a very useful Java program (key Code) (eight)---Java InputStream read the network response response data Method! Important

Java InputStream Read Data problems

======================================================================

principle Explanation


1. About Inputstream.read ()
When reading data from a data stream, it is easy to use the Inputstream.read () method for diagrams.     This method is to read one byte at a time from the stream and is very inefficient. A better approach is to read multiple bytes at a time using Inputstream.read (byte[] b) or Inputstream.read (byte[] B,int Off,int len) methods.

2. Available () method for the InputStream class
To read more than one byte at a time, the Inputstream.available () method is often used, which allows you to know how many bytes in the data stream can be read before the read and write operation. It is important to note that if this method is used in the
When the data is read by the file, it is generally not a problem, but if it is used for network operation, it often encounters some trouble. For example, the socket communication, the Fangmingming sent 1000 bytes, but its own program calls available () method only get 900, or 100, or even 0, feel a bit inexplicable, how can not find the reason. In fact, this is because network traffic is often intermittent, a string of bytes are often divided into several batches to send. The local program call available () method sometimes gets 0, which may be that the other party has not responded, or it may have responded, but the data has not been delivered locally. The other side sends 1000 bytes to you, perhaps into 3 batches, which you will call 3 times available () method to get the total number of data.
If you write code like this:

  int count = In.available ();  Byte[] B = new Byte[count];  In.read (b);

in the network operation is often error, because when you call the available () method, the data sent to the send may not have arrived, you get the count is 0.
Need to change to this:

int count = 0;    while (count = = 0)   {//count = in.available ();    Count=response.getentity (). Getcontentlength (); // (httpresponse response)   }  bytenewbyte[count];  In.read (b);

3. With regard to Inputstream.read (byte[] b) and Inputstream.read (byte[] b,int Off,int len) Both methods are used to read multiple bytes from the stream, and experienced programmers will find that these two methods are often You cannot read the number of bytes that you want to read. For example, the first method, programmers often want the program to read B.length bytes, and the reality is that the system is often not read so much. A closer look at the Java API description reveals that this method does not guarantee that you can read so many bytes, it can only guarantee to read so many bytes (at least 1). Therefore, if you want a program to read count bytes, it is best to use the following code:

byte New byte [Count];   int // The number  of bytes that have been successfully read  while (Readcount < count) {   + = in.read (bytes, readcount, Count- readcount);  }

Use this code to ensure that count bytes are read unless an IO exception is encountered halfway through or at the end of the data stream (eofexception).

==========================================================================================

Code sharing

The following share my own written test code snippet, for your reference:

/*** <b> Gets the data information returned by the specified URL </b> *@param<font color= "#efac10" ><a href= "http://www.baidu.com">_url: Specified url</a></font> *@return     * @throwsclientprotocolexception *@throwsIOException*/     PublicString Getreponse (String _url)throwsclientprotocolexception, IOException {String readcontent=NULL; Defaulthttpclient httpclient=Newdefaulthttpclient (); HttpGet HttpGet=NewHttpGet (Sinajsontest.sinaurl); System.out.println ("0.Send the URL to Sina Sever ..."); HttpResponse Response=Httpclient.execute (HttpGet); Httpentity Entity=response.getentity (); System.out.println ("1.Get Response Status:" +response.getstatusline ()); if(Entity! =NULL) {System.out.println ("Get responsecontentencoding ():" +entity.getcontentencoding ()); System.out.println ("Content Length ():" +entity.getcontentlength ()); //GetResponseInputStream in=entity.getcontent (); intCount = 0;  while(count = = 0) {Count= Integer.parseint ("" +entity.getcontentlength ());//in.available ();            }            byte[] bytes =New byte[Count]; intReadcount = 0;//The number of bytes that have been successfully read             while(Readcount <=count) {             if(Readcount = = count) Break; Readcount+ = In.read (bytes, readcount, Count-readcount); }                        //Convert to StringReadcontent=NewString (bytes, 0, Readcount, "UTF-8");//Convert to string using bytesSystem.out.println ("2.Get Response Content (): \ n" +readcontent); }        returnreadcontent; }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Share a very useful Java program (key Code) (eight)---Java InputStream read the network response response data Method! Important

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.