我知道曾经有一种方法可以通过apache commons来获取它,如下所示:http: //hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html 以及此处的示例:
http://www.kodejava.org/examples/416.html
但我相信这已被弃用了.是否还有其他方法可以在java中生成http get请求并将响应主体作为字符串而不是流来获取?
我有一个Android客户端,通过REST-ful端点和JSON与服务器通信.因此,我需要在将其转换为Hash之前检索完整的服务器响应.我有这个代码(在互联网上找到的地方):
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)
代码在大多数情况下都有效,但是我看到来自具有OutOfMemory异常的客户端在该字段中崩溃的报告:
while ((line = reader.readLine()) != null) {
Run Code Online (Sandbox Code Playgroud)
完整的堆栈跟踪是:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124) …Run Code Online (Sandbox Code Playgroud) 我从成千上万的角色成长为指数大的String test += str;地方test.运行需要45分钟,可能是因为创建了大字符串并删除了垃圾.然后,我将这样的输入交错,使其达到30秒.
这似乎是一种廉价的方式,但效果很好:
if (secondDump.length() > 50)
{
intermedDump = intermedDump + secondDump;
secondDump = "";
}
if (intermedDump.length() > 100)
{
thirdDump = thirdDump + intermedDump;
intermedDump = "";
}
if (thirdDump.length() > 500)
{
fourthDump = fourthDump + thirdDump;
thirdDump = "";
}
if (fourthDump.length() > 1000)
{
fifthDump = fifthDump + fourthDump;
fourthDump = "";
}
//with just this and not sixth. Runtime>>>> : 77343
if (fifthDump.length() > 5000)
{
sixthDump …Run Code Online (Sandbox Code Playgroud)