-1

我正在尝试读取缓冲区(android 应用程序)并将值设置为我的TextView 'httpStuff'. 但我认为我没有从 URI 中得到一些响应。

我没有收到任何运行时错误。我尝试了许多相同逻辑的味道。似乎没有任何工作。

INTERNET清单中已经设置了权限。SdkVersion="15". 有什么帮助吗?

HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.mybringback.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity(); 
InputStream is = entity.getContent(); 
BufferedReader in = new BufferedReader(new InputStreamReader(is));

httpStuf.setText( in.readLine());
4

4 回答 4

2

我认为你错过了 while 循环,而且,当你说 only 时in.readLine(),可能是它从响应中返回一个空行,尽管它有足够的数据。所以请确保完全像这样阅读阅读器并检查其内容.

while ((line = rd.readLine()) != null) {
    httpStuf.setText(line+"\r\n");
}

希望这会帮助你。

于 2012-05-30T04:42:49.683 回答
1

这段代码对我有用

  InputStream is = response.getEntity().getContent();
  String strResponse = inputStreamToString(is);


private String inputStreamToString(InputStream is)
{

    String line = "";
    StringBuilder total = new StringBuilder();
    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024 * 4);
    // Read response until the end
    try
    {

        while ((line = rd.readLine()) != null)
        {
            total.append(line);
        }
    } catch (IOException e)
    {
        Log.e(TAG, "error build string" + e.getMessage());
    }
    // Return full string
    return total.toString();
}
于 2012-05-30T04:45:05.630 回答
0

尝试获取 and 的状态码,response然后可以与(HTTP状态)进行比较

int responseCode=response.getStatusLine().getStatusCode()

于 2012-05-30T04:39:36.477 回答
0

我正在使用这种方法来简单地捕获 HTTP 响应,它对我来说很好用。

public String httpGetResponse(String url) {
        try {
            Log.i("HTTP Request", "httpGet Request for : " + url);
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            //get.setHeader("Connection", "keep-alive");

            HttpResponse response = client.execute(get);

            InputStream is = response.getEntity().getContent();
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(is));
            StringBuilder str = new StringBuilder();

            String line = null;

            while ((line = bufferedReader.readLine()) != null) {
                str.append(line + "\n");
            }
            return str.toString();
        } catch (Exception e) {
            Log.e("HTTP error", "Error in function httpGetResponse : "
                    + e.getMessage());
            return null;
        }
    }
于 2012-05-30T05:37:18.763 回答