为什么我在String中收集的xml输出格式不正确?

时间:2013-10-21 13:33:04

标签: java android xml cakephp xml-parsing

我正在尝试从Web服务获取xml,并将其存储在字符串中。我需要在Log cat中打印这个xml,但它没有以正确的方式出现。  代码是:

MainActivity.java

public class MainActivity extends Activity {
    static final String URL = myUrlOfLocalHost;

    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_NAME = "name";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";
    private String xml;

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AsyncTaskRunner runner = new AsyncTaskRunner();
        runner.execute();

    }

    class AsyncTaskRunner extends AsyncTask<String, String, String> {

        @SuppressLint("NewApi")
        @Override
        protected String doInBackground(String... params) {

            publishProgress("Sleeping..."); // Calls onProgressUpdate()
            ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

            XMLParser parser = new XMLParser();

            xml = parser.getXmlFromUrl(URL); // getting XML
            //Document doc = parser.getDomElement(xml); // getting DOM element



            Log.e("String Data : " , xml);
return null;
}

XMLParser.java

public class XMLParser {


    private StringBuffer result ;

    //Method to get XML from reuested URL
    public String getXmlFromUrl(String url) {

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            //xml = EntityUtils.toString(httpEntity);

            InputStream in = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"),8);
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                // sb.append(line);
                result =  sb.append(line);;
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML complete
        return result.toString();
    }

请建议任何解决方案,因为logcat中的输出如下所示:

<pre class="cake-error"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5265202999359-trace').style.display = (document.getElementById('cakeErr5265202999359-trace').style.display == 'none' ? '' : 'none');"><b>Notice</b> (8)</a>: Undefined variable: school [<b>APP\View\Schools\xml\get_school_details.ctp</b>, line <b>1</b>]<div id="cakeErr5265202999359-trace" class="cake-stack-trace" style="display: none;"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5265202999359-code').style.display = (document.getElementById('cakeErr5265202999359-code').style.display == 'none' ? '' : 'none')">Code</a> <a href="javascript:void(0);" onclick="document.getElementById('cakeErr5265202999359-context').style.display = (document.getElementById('cakeErr5265202999359-context').style.display == 'none' ? '' : 'none')">Context</a><pre id="cakeErr5265202999359-code" class="cake-code-dump" style="display: none;"><span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">&lt;?php&nbsp;$xml&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">Xml</span><span style="color: #007700">::</span><span style="color: #0000BB">fromArray</span><span style="color: #007700">(array(</span><span style="color: #0000BB">$school</span><span style="color: #007700">));</span></span></code></span></pre><pre id="cakeErr5265202999359-context" class="cake-context" style="display: none;">$viewFile = &#039;C:\wamp\www\School App\app\View\Schools\xml\get_school_details.ctp&#039;$dataForView = array()</pre><pre class="stack-trace">include - APP\View\Schools\xml\get_school_details.ctp, line 1View::_evaluate() - CORE\Cake\View\View.php, line 931View::_render() - CORE\Cake\View\View.php, line 893View::render() - CORE\Cake\View\View.php, line 462XmlView::render() - CORE\Cake\View\XmlView.php, line 104Controller::render() - CORE\Cake\Controller\Controller.php, line 952Dispatcher::_invoke() - CORE\Cake\Routing\Dispatcher.php, line 194Dispatcher::dispatch() - CORE\Cake\Routing\Dispatcher.php, line 162[main] - APP\webroot\index.php, line 110</pre></div></pre><?xml version="1.0" encoding="UTF-8"?><response>  <code>500</code>  <url>/School%20App/schools/getSchoolDetails.xml?school_id=1</url>  <name>The key of input must be alphanumeric</name></response>

在服务器端使用的方法(代码)是:

public function getSchoolDetails() {
    if ($this->RequestHandler->isXml() && $this->request->is('get')) {
        $this->School->unBindModel(array('hasMany' => array('Admin', 'Announcement', 'Batch', 'Class1', 'Event', 'Lunchmenu', 'Student', 'Timetable', 'SpecialInstruction'),                                         'hasAndBelongsToMany' => array('Subject')));
        $fields = array('School.id, School.school_name, School.logo, School.phone');
        $school = $this->School->find('first', array('fields' => $fields, 'conditions' => array('School.id' => $_GET['school_id'])));
        $this->set(array(
            'school' => $school,
        '_serialize' => array('school')
        ));
    }
}

2 个答案:

答案 0 :(得分:0)

如果这是在logcat中,那么它看起来像是服务器上的php问题......

....CORE\Cake\Routing\Dispatcher.php....

答案 1 :(得分:0)

您正在使用POST请求,而您的控制器操作仅适用于GET请求:

if ($this->RequestHandler->isXml() && $this->request->is('get')) {

这会导致在非XML / POST请求时不设置变量,从而导致您收到错误。

快速修复,也允许POST个请求或使用GET请求。此外,我建议更改您的控制器操作,以便在请求不符合要求时触发正常的例外。这是一个(未经测试的)示例,看起来像是:

public function getSchoolDetails() {
    // NOTE you don't necessarily need this, you could also force the type
    // of response using $this->RequestHandler->renderAs($this, 'xml');
    if (!$this->RequestHandler->isXml()) {
        throw new BadRequestException();
    }

    // NOTE as of CakePHP 2.3 you could use $this->request->onlyAllow('get');
    // instead
    if (!$this->request->is('get')) {
        throw new MethodNotAllowedException();
    }

    // NOTE use the request object instead of $_GET, it will safely return
    // null on non-existent parameters
    $id = $this->request->query('school_id');

    // NOTE skip this in case you want to retrieve empty results instead
    if (!$this->School->exists($id)) {
        throw new NotFoundException();
    }

    // NOTE you should use the containable behavior instead of this
    // unbinding orgy
    $this->School->unbindModel(array(
        'hasMany' => array(
            'Admin', 'Announcement', 'Batch', 'Class1',
            'Event', 'Lunchmenu', 'Student', 'Timetable',
            'SpecialInstruction'
        ),
        'hasAndBelongsToMany' => array(
            'Subject'
        )
    ));

    $fields = array(
        'School.id, School.school_name, School.logo, School.phone'
    );
    $school = $this->School->find('first', array(
        'fields' => $fields,
        'conditions' => array(
            'School.id' => $id
        )
    ));

    $this->set(array(
        'school' => $school,
        '_serialize' => array('school')
    ));
}