0

我想要做的是从一个 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();
}

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();但我不确定。

4

1 回答 1

3

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());
    }
}
于 2013-04-26T13:07:50.630 回答