微博提供Java版本的SDK竟然是Beta版weibo4j-oauth2-beta3.1.1

运行示例的时候出现了这样的警告:

1
Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommend

检索代码出现在weibo4j.http.HttpClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public Response httpRequest(HttpMethod method, Boolean WithTokenHeader, String token) throws WeiboException {
InetAddress ipaddr;
int responseCode = -1;
try {
ipaddr = InetAddress.getLocalHost();
List<Header> headers = new ArrayList<Header>();
if (WithTokenHeader) {
if (token == null) {
throw new IllegalStateException("Oauth2 token is not set!");
}
headers.add(new Header("Authorization", "OAuth2 " + token));
headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress()));
client.getHostConfiguration().getParams()
.setParameter("http.default-headers", headers);
for (Header hd : headers) {
log(hd.getName() + ": " + hd.getValue());
}
}

method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
client.executeMethod(method);
Header[] resHeader = method.getResponseHeaders();
responseCode = method.getStatusCode();
log("Response:");
log("https StatusCode:" + String.valueOf(responseCode));

for (Header header : resHeader) {
log(header.getName() + ":" + header.getValue());
}
Response response = new Response();
response.setResponseAsString(method.getResponseBodyAsString());
response.setResponseAsString(stringBuffer.toString());
log(response.toString() + "\n");

if (responseCode != OK)
{
try {
throw new WeiboException(getCause(responseCode),
response.asJSONObject(), method.getStatusCode());
} catch (JSONException e) {
e.printStackTrace();
}
}
return response;

} catch (IOException ioe) {
throw new WeiboException(ioe.getMessage(), ioe, responseCode);
} finally {
method.releaseConnection();
}

}
```
原因就是没有字符缓冲,可能因为响应字符过长,而影响效率, 因此从第396行改为:

// old code response.setResponseAsString(method.getResponseBodyAsString());
InputStream inputStream = method.getResponseBodyAsStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String temp ;
while ((temp=bufferedReader.readLine())!=null){
stringBuffer.append(temp);
}
response.setResponseAsString(stringBuffer.toString()); 

`