在Android中管理HTTP响应

时间:2012-04-26 06:49:46

标签: android http android-2.3-gingerbread

我正在从android中的AsyncTask向服务器发出HTTP post请求请求。

我在管理响应方面面临的问题。我在这里如何阅读回复。

HttpEntity entity =response.getEntity();
if (entity != null) {

    DataInputStream in = new DataInputStream( entity.getContent());
    String str;
    while (( str = in.readLine()) != null){


    Log.e("Debug","Server Response second url"+str); 

 }
   in.close();
}

问题是我得到了片断的回应,但我希望它们是一体的

当前回复

 Server Response second url
 Server Response second url<header><status>Success</status><message>Check the Numbers:
 Server Response second url123456.</message><vbal>5005</vbal></header>

预期回复

<header><status>Success</status><message>Check the Numbers:123456.</message><vbal>5005</vbal></header>

如果我将它整合在一起,我可以轻松地解析xml响应并获取所需的值。

2 个答案:

答案 0 :(得分:1)

这应该适合你:

StringBuilder sb = new StringBuilder();
String str;
while ((str = in.readLine()) != null) {
    sb.append(str);
}
in.close();
str = sb.toString(); //here you have the string you need.
Log.e("Debug","Server Response second url" + str); 

答案 1 :(得分:1)

如果你有Apache commons:

Reader in = new InputStreamReader(entity.getContent(), "UTF-8");

StringWriter writer = new StringWriter();
IOUtils.copy(in, writer);

String str = writer.toString();

否则,

final char[] buffer = new char[0x10000];
StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(entity.getContent(), "UTF-8");

try {
    int read;

    do {
        read = in.read(buffer, 0, buffer.length);
        if (read > 0)
            out.append(buffer, 0, read);
    } while (read >= 0);
} finally {
  in.close();
}

String str = out.toString();