0

私がやろうとしているのは、URL からバイト配列を生成することです。

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

返されるurljson

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-ioを使用してバイトを読み取ることを検討してください。InputStream

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 に答える