HttpURLConnection输出到字节数组然后输出到String

时间:2014-04-15 20:13:55

标签: java

我正在读取HttpURLConnection对象对String的响应,如下所示:

HttpURLConnection conn = ...;
BufferedReader rd = new BufferedReader(new InputStreamReader(
    conn.getInputStream());

StringBuilder sb = ...;
String line = "";
while ((line = rd.readLine()) != null) {
    sb.append(line);
}

String asString = sb.toString();

如果我想首先读取字节数组,然后将该字节数组转换为字符串,那么正确的方法是什么?

InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream(16384);
byte[] buf = new byte[512];
while (true) {
    int len = in.read(buf);
    if (len == -1) {
        break;
    }
    baos.write(buf, 0, len);
}

byte[] out = baos.toByteArray();

// as a string:
String asString = new String(out);

但我在两种情况下都没有指定字符 - 示例末尾的两个字符串输出是等效的吗?

由于

0 个答案:

没有答案