HTTP-запрос для XML-файла - PullRequest
       5

HTTP-запрос для XML-файла

13 голосов
/ 02 марта 2011

Я пытаюсь использовать Flurry Analytics для своей программы на Android, и у меня возникают проблемы при получении самого файла xml с сервера.

Я подхожу близко, потому что в теге Log Cat System.out я могу получить половину из этого по какой-то причине, и он говорит: «Исключение при передаче XML = java.net.MalformedURLException: Протокол не найден:? Xml version = 1.0 encoding = "UTF-8" и т. Д. ... примерно до половины моего xml-кода. Не уверен, что я делаю неправильно, я отправляю HTTP-запрос с заголовком, запрашивающим принять application / xml, и он не работает должным образом Любая помощь приветствуется!

try {

                //HttpResponse response = client.execute(post);
                //HttpEntity r_entity = response.getEntity();
                //String xmlString = EntityUtils.toString(r_entity);

        HttpClient client = new DefaultHttpClient();  
        String URL = "http://api.flurry.com/eventMetrics/Event?apiAccessCode=????&apiKey=??????&startDate=2011-2-28&endDate=2011-3-1&eventName=Tip%20Calculated";
        HttpGet get = new HttpGet(URL);
        get.addHeader("Accept", "application/xml");
        get.addHeader("Content-Type", "application/xml");
        HttpResponse responsePost = client.execute(get);  
        HttpEntity resEntity = responsePost.getEntity(); 
        if (resEntity != null) 

        {  
                    System.out.println("Not null!");

                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

                    DocumentBuilder db = dbf.newDocumentBuilder();

                    String responseXml = EntityUtils.toString(responsePost.getEntity());
                    Document doc = db.parse(responseXml);
                    doc.getDocumentElement().normalize();

                    NodeList nodeList = doc.getElementsByTagName("eventMetrics");


                    for (int i = 0; i < nodeList.getLength(); i++)
                    {
                        Node node = nodeList.item(i);   

                        Element fstElmnt = (Element) node;

                        NodeList nameList = fstElmnt.getElementsByTagName("day");

                        Element dayElement = (Element) nameList.item(0);

                        nameList = dayElement.getChildNodes();

                        countString = dayElement.getAttribute("totalCount");
                        System.out.println(countString);
                        count = Integer.parseInt(countString);
                        System.out.println(count);
                        count += count;

                    }
        }

    } catch (Exception e) {

                    System.out.println("XML Passing Exception = " + e);

                }

Ответы [ 2 ]

18 голосов
/ 02 марта 2011

Метод синтаксического анализа, который принимает строку, предназначен для формата URL. Вам нужно обернуть String в StringReader перед его разбором. Еще лучше, если вы можете взять XML как InputStream и проанализировать его, что-то вроде:

String uri =
    "http://api.flurry.com/eventMetrics/Event?apiAccessCode=?????&apiKey=??????&startDate=2011-2-28&endDate=2011-3-1&eventName=Tip%20Calculated";

URL url = new URL(uri);
HttpURLConnection connection =
    (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");

InputStream xml = connection.getInputStream();

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xml);
0 голосов
/ 02 февраля 2018

Я использовал HttpURLConnection, и это рабочий код.

URL url = new URL("....");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Accept", "application/xml");
httpConnection.setRequestProperty("Content-Type", "application/xml");

httpConnection.setDoOutput(true);
OutputStream outStream = httpConnection.getOutputStream();
OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
outStreamWriter.write(requestedXml);
outStreamWriter.flush();
outStreamWriter.close();
outStream.close();

System.out.println(httpConnection.getResponseCode());
System.out.println(httpConnection.getResponseMessage());

InputStream xml = httpConnection.getInputStream();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...