Android HttpEntity对象......重用它的最佳方法是什么?

时间:2011-06-15 09:05:54

标签: android http entity

我正在使用正在执行http GET请求的软件,然后我收到了HttpEntity响应。 这对我来说没问题。问题是我想使用2次读取此响应,我不知道哪种方式最好。

如果我将实体转换为字符串,那么当我尝试再次访问该实体时,我会得到一个实例已被消耗的异常。

如果我尝试使用getContent方法来使用InputStream,我找不到根据需要重新读取inputStream的方法。

有人可以告诉我如何将httpEntity结果保存为可以重复使用两次的方法吗?我创建了一个文件?我怎么做的?每次执行GET时写入文件的性能如何?如何在每次通话时删除该文件?保存文件的位置?

如果您有任何其他想法,感谢您的帮助。 我将欣赏代码示例。

1 个答案:

答案 0 :(得分:0)

我终于找到了如何将流转换为字符串,所以我做了以下事情:

    //Get the answer from http request
    if(httpResponse!=null)
        entity = httpResponse.getEntity();
    else
        entity = null;

    //Display the answer in the UI
    String result;
    if (entity != null) {
                    //First, Open a file for writing
        FileOutputStream theXMLFile=null;
        try{
            theXMLFile=openFileOutput("HttpResponse.dat", MODE_PRIVATE);
        } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e("ResultService Exception :", e.getMessage());
        }

        try {
            if(theXMLFile!=null) {
                                    //Save the stream to a file to be able to re read it later.
                entity.writeTo(theXMLFile);
                                    //Entity is consumed now and cannot be reuse ! Lets free it.
                entity=null;

                                    //Now, lets read this file !
                FileInputStream theXMLStream=null;
                try {
                    //Open the file for reading and convert to a string
                    theXMLStream = openFileInput("HttpResponse.dat");
                    result=com.yourutilsfunctionspackage.ServiceHelper.convertStreamToString(theXMLStream);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.e("ResultService Exception :", e.getMessage());
                    result=null;
                }
                theXMLStream.close();
                theXMLStream=null;

                //Use the string for display
                if(result!=null)
                    infoTxt.setText(getText(R.string.AnswerTitle) + " = " +result);

try {
//Reopen the file because you cannot use a FileInputStream twice.
theXMLStream = openFileInput("HttpResponse.dat");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ResultService Exception :", e.getMessage());
}



//Re use the stream as you want for decoding xml                
if(theXMLStream!=null){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder=null;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if(builder!=null)
    {
        Document dom=null;
        try {
            dom = builder.parse(theXMLStream);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        if(dom!=null){
            Element racine = dom.getDocumentElement();
            NodeList nodeLst=racine.getElementsByTagName("response");
            Node fstNode = nodeLst.item(0);
            if(fstNode!=null){
                Element fstElmnt = (Element) fstNode;
                String CallingService=fstElmnt.getAttribute("service");

etc....

//Function taken from internet http://www.kodejava.org/examples/266.html
public static String convertStreamToString(InputStream is) throws IOException {
        /*
         * To convert the InputStream to String we use the
         * Reader.read(char[] buffer) method. We iterate until the
         * Reader return -1 which means there's no more data to
         * read. We use the StringWriter class to produce the string.
         */
        if (is != null) {
            Writer writer = new StringWriter();


        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {       
        return null;
    }
}