简体   繁体   中英

HttpURLConnection returning only few bytes

I have:

InputStream input = null;
HttpURLConnection connection = null;
URL url = new URL("...");

connection = (HttpURLConnection) url.openConnection();
String zam = "...";
connection.setRequestProperty("Cookie",zam);
connection.connect();

int fileLength = connection.getContentLength();
input = connection.getInputStream();
byte data[] = new byte[400];
int count;
count = input.read(data);
connection.disconnect();
String str1 = new String(data);

str1, the response is always only:

!DOCTYPE HTML PUBLIC "-/

nothing more. But when I turn off the cookie:

connection.setRequestProperty("Cookie",zam);

everything is OK;

Thanks ind adv for reply. Adi.

I guess the problem is that you don't read all the data from the stream. Try to use a method like this.

public static String streamToString(final InputStream is, final int bufferSize) throws Exception {
    final char[] buffer = new char[bufferSize];
    final StringBuilder out = new StringBuilder();
    try (Reader in = new InputStreamReader(is, "UTF-8")) {
        int rsz = 0;
        while ((rsz = in.read(buffer, 0, buffer.length)) > 0) {
            out.append(buffer, 0, rsz);
        }
    }
    return out.toString();
}

And also read this answer about other methods How do I read / convert an InputStream into a String in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM