java - 从 StringBuffer.toString 生成字节数组

标签 java android

我想做的是从 url 生成一个字节数组。

byte[] data = WebServiceClient.download(url);

url 返回 json

public static byte[] download(String url) {
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    try {
        HttpResponse response = client.execute(get);
        StatusLine status = response.getStatusLine();
        int code = status.getStatusCode();
        switch (code) {
            case 200:
                StringBuffer sb = new StringBuffer();
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                is.close();

                sContent = sb.toString();

                break;       
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return sContent.getBytes();
}

数据用作String的参数

String json = new String(data, "UTF-8");
JSONObject obj = new JSONObject(json);

由于某种原因,我收到此错误

I/global  (  631): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.

我认为这里肯定缺少一些东西 sContent = sb.toString(); 或这里 return sContent.getBytes(); 但我不确定。

最佳答案

1.考虑使用 Apache commons-ioInputStream

读取字节
InputStream is = entity.getContent();
try {
    return IOUtils.toByteArray(is);
}finally{
    is.close();
}

目前,您没有必要将字节转换为字符并返回。

2. 避免使用 String.getBytes() 而不将字符集作为参数传递。而是使用

String s = ...;
s.getBytes("utf-8")

<小时/> 总的来说,我会重写你的方法,如下所示:

public static byte[] download(String url) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    HttpResponse response = client.execute(get);
    StatusLine status = response.getStatusLine();
    int code = status.getStatusCode();
    if(code != 200) {
        throw new IOException(code+" response received.");
    }
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    try {
        return IOUtils.toByteArray(is);
    }finally{
        IOUtils.closeQuietly(is.close());
    }
}

关于java - 从 StringBuffer.toString 生成字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16237065/

相关文章:

java - 在文件中搜索与给定条件匹配的行

java - 将内容(url)包含到 jsp 中

安卓共享偏好

android - 带有 url 的 intent-filter - 我们如何限制范围?

android - 如何使用 Android 的架构组件从 ViewModel 完成 Activity ?

java - 如何保存可见性android

android - 用于调整大小的 LinearLayout layout_weight 和 weight_sum?

java - 在 OS X 10.9 上安装 Java(小牛)

java - 定义像 #define 这样的常量,可以在 java 中的 switch 语句中使用

java - 矩阵到字符串输出