【问题标题】:how do I get a string from my http response android?如何从我的 http 响应 android 中获取字符串?
【发布时间】:2013-03-25 15:35:08
【问题描述】:

我见过一些看起来很丑陋的代码,人们编写了自己的将 HttpResponse 转换为字符串以供以后使用的方法,看起来像这样:

httppost.setEntity(new UrlEncodedFormEntity(valuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
}
is.close();
String result = sb.toString();

这不仅有点乱,而且真的很丑陋,而且我经常无法判断代码发生了什么,因为它之前是乱七八糟的。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: android string http httpresponse


    【解决方案1】:

    是的,有!您可以在一条线上完成所有这些!像这样:

    response = client.execute(post);
    String responseStr = EntityUtils.toString(response.getEntity());
    

    快乐的应用制作

    【讨论】:

    • 这有一个问题。如果响应是 gzip 压缩的,这将不起作用。你必须调用'InputStream stream = AndroidHttpClient.getUngzippedContent(response.getEntity());'然后将 InputStream 转换为字符串。我还没有找到更好的方法。
    • 可能在 2013 年工作,但在 2016 年不行!这是我的错误 - > 方法抛出了 'java.lang.IllegalStateException' 异常。
    【解决方案2】:

    我使用来自HttpClient.execute documentation 的响应处理程序完成了它。使用处理程序作为 .execute 方法的第二个参数定义了响应的格式。
    我的代码如下:

    HttpClient client = new DefaultHttpClient();
    
            HttpGet request = new HttpGet(params[0]);
            ResponseHandler<String> handler = new BasicResponseHandler();
            String response = "";
            try {
                response = client.execute(request, handler);
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    params[0] 是一个字符串形式的 URL。说我的服务器以 JSON 格式返回响应可能很重要。所以最后我将我的 response 字符串转换为 JSON。

    【讨论】:

    • 非常适合我,我的促销代码验证服务器返回纯字符串“VALID”或“INVALID”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2011-03-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多