从StringBuffer.toString生成字节数组

时间:2013-04-26 12:57:40

标签: java android

我要做的是从网址生成一个字节数组。

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();
}

data用作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 个答案:

答案 0 :(得分:3)

1。考虑使用Apache commons-ioInputStream读取字节

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

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

2. :不将charset作为参数传递,避免使用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());
    }
}