【问题标题】:HttpGet response string truncatedHttpGet 响应字符串被截断
【发布时间】:2014-08-13 03:32:50
【问题描述】:

我正在使用httpGet。但我得到的答复不完整。只是为了测试,我使用了另一个 URL,为此我的代码工作正常,但对于我的实际链接,我的响应被截断。我已经推荐了this 解决方案,但它对我不起作用。请建议我如何解决这个问题。

这是我所做的:

private HttpGet httpGet;
private HttpClient client;
private String url;

httpGet = new HttpGet(url);
try{
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    data = client.execute(httpGet, responseHandler);

    Log.i(LOG_TAG, "Response :: " + data);

    returnClass = getMapper().readValue(data, responseType);
    Log.i(LOG_TAG, "URL :: " + url + " Completed");
}finally{
    client.getConnectionManager().shutdown();
}

【问题讨论】:

  • @Rod_Algonquin 查看我编辑的代码
  • 代码不完整。什么是数据?进一步:您认为the response 是什么?您确实没有流式传输响应。其余的:这个网站上有很多例子向你展示了如何做到这一点。稍微搜索一下。
  • data 是我的字符串变量。在日志中我正在打印数据,但只有我得到不完整的响应。
  • 如果响应很大,即使您收到完整的响应,logcat 也不总是显示完整的文本。
  • 如果你的字符串很大,logcat 不会全部显示。您可以尝试将您的字符串分成约 4k 的片段并在 logcat 上查看,或者只查看字符串长度并感到满意。

标签: android http-get androidhttpclient


【解决方案1】:

也许您的消息太长,logcat 无法显示。

您可能会得到完整的 HTTP 答案,但 logcat 只向您显示字符串的一部分。

编辑:正如我在 cmets 中所说,您可以尝试使用 HttpURLConnection 而不是 HttpClientHttpGet。比如下面的例子:

HttpURLConnection urlConnection = null;
BufferedReader reader = null;

...

try {
    URL url = new URL("Your URL here");
    // Open the connection
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();

    // Read the input stream into a String
    InputStream inputStream = urlConnection.getInputStream();
    StringBuffer buffer = new StringBuffer();
    if (inputStream == null) {
        // Nothing to do.
        return null;
    }
    reader = new BufferedReader(new InputStreamReader(inputStream));

    String line;
    while ((line = reader.readLine()) != null) {
        // Adding new line mark.
        buffer.append(line + "\n");
    }

    if (buffer.length() == 0) {
        // Stream was empty.
        return null;
    }
    return buffer.toString();
} catch (IOException e) {
    Log.e(LOG_TAG, "Error ", e);                
    return null;
} finally{
    if (urlConnection != null) {
        urlConnection.disconnect();
    }
    if (reader != null) {
        try {
            reader.close();
        } catch (final IOException e) {
            Log.e(LOG_TAG, "Error closing stream", e);
        }
    }
}

【讨论】:

  • 这并没有真正提供问题的答案。你只是假设问题可能是什么。 @ShivamVerma 在问题的 cmets 中已经完成了这项工作。此外,另一条评论已经提到可以做些什么来解决这个问题。您能否为已经给出的 cmets 提供任何附加值(例如,完整的解决方案)?
  • 对不起,我没有看到评论。好吧,当这发生在我身上时,问题真的出在其他地方,我被 logcat 上的截断消息误导了。但是,如果您认为问题确实出在这部分代码中,您是否考虑过使用 HttpURLConnection 而不是 HttpClient?我会用一个例子来编辑我的答案。
  • 感谢您提供代码。你的答案现在看起来好多了!
  • 不客气!很抱歉第一个蹩脚的答案。我是新来的哈哈。以后告诉我它是否有效!
  • 无需为自己辩解。我们都开始了一段时间。你已经证明是合作的。这是非常好的。顺便说一句,我并没有亲自寻找解决方案。我经常审查新人的帖子,并尝试给他们一些启动帮助。这背后的想法是在 Stack Overflow 上保持高质量的答案(以及问题)。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 1970-01-01
  • 2014-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
相关资源
最近更新 更多