gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:51:33 24 4
gpt4 key购买 nike

我想做的是从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com