-1

I am trying to get an XML file from a url using HTTP Get method in Android. When I enter the url in my browser I get the XML file. However when I try and use HttpURLConnection in Android, the input stream is always null. I am trying to figure out the problem but in vain. I would like some help in understanding the problem.
Here are my codes:
XML File

<?xml version="1.0" encoding="UTF-8"?>
<item>
    <log>27.1823000000</log>
    <lat>88.5012200000</lat>
</item>

Async Task

private class GetOnlineData extends AsyncTask<Void, Void, String>{

        @Override
        protected String doInBackground(Void... voids){
            String latlog=null;

            // Accessing link to obtain XML file
            try{
                URL url = new URL(link);
                HttpURLConnection htc = (HttpURLConnection) url.openConnection();
                inputStream = htc.getInputStream();
            }catch(Exception e){}

            // Parsing XML data from input stream
            if(inputStream!=null){
                try {
                    DocumentBuilderFactory xmlparser = DocumentBuilderFactory.newInstance();
                    DocumentBuilder dBuilder = xmlparser.newDocumentBuilder();
                    Document dc = dBuilder.parse(inputStream);

                    Element ele = dc.getDocumentElement();
                    ele.normalize();

                    NodeList nodeList = dc.getElementsByTagName("item");

                    for (int i=0; i<nodeList.getLength(); i++){
                        Node node = nodeList.item(i);
                        if(node.getNodeType() == Node.ELEMENT_NODE){
                            Element ele2 = (Element) node;
                            latlog = "Longitude: "+getValue("log",ele2)+"\n";
                            latlog += "Latitude: "+getValue("lat",ele2);
                        }
                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
            }

            return latlog;
        }

        @Override
        protected void onPostExecute(String latlog){
            if(inputStream==null) {
                Toast.makeText(getApplicationContext(), "Didn't Work", Toast.LENGTH_SHORT).show();
            } else {
                textView.setText(latlog);
            }
        }
    }

getValue(String, Element)

private static String getValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = nodeList.item(0);
        return node.getNodeValue();
    }
dannyBoy
  • 67
  • 13
  • XML is kinda a old way why not switch to JSON ? Simple and nice – teck wei Dec 29 '16 at 16:38
  • For that, I will need to know how to send _json_ object using _python-cgi-script_ . Can you point me out a decent tutorial on how to do that? It would be really helpful. @teckwei – dannyBoy Dec 29 '16 at 16:43
  • Hmm.. i'm using php for server side. 0 knowledge on python I bet you could google it. – teck wei Dec 29 '16 at 16:45
  • Try to analyze response code: 'int responseCode = htc .getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = htc.getInputStream();... }`. May be there is server error like unauthorized access and so on. And probably `HttpURLConnection` should be configured like `htc .setRequestMethod("GET"); htc.connect(); ` or something like that. – Andrii Omelchenko Dec 29 '16 at 16:53
  • The response code was indeed **403**, so I added the line `htc.setRequestMethod("GET")` Even then the response code was **403**
    – dannyBoy Dec 29 '16 at 17:02
  • So I checked the link in the phone browser I was testing the app in, and the xml page showed properly, as it should have. @AndriyOmelchenko – dannyBoy Dec 29 '16 at 17:05
  • Take a look at [this](https://en.wikipedia.org/wiki/HTTP_403) - the issue is not in your code, but in access to server. May be URL is wrong (typo in URL) - so check `link` value before `URL url = new URL(link);`. – Andrii Omelchenko Dec 29 '16 at 17:17

1 Answers1

1

Seems issue is not in your source code, but in access to server. May be URL is wrong (typo in URL) - so check link variable value before call

URL url = new URL(link);

may be some parameters missing. And try to analyze response code:

int responseCode = htc.getResponseCode(); 
if (responseCode == HttpURLConnection.HTTP_OK) { 
    inputStream = htc.getInputStream();
    ... 
}

And probably HttpURLConnectionshould be configured likehtc.setRequestMethod("GET");` or something like that: HTTP Authentication, Proxy, Cookies and so on (see Official Documentation).

Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
  • The problem was indeed with my server. I checked the error log of the server and it showed that _mod-security-anormalies_ was rejecting the request due to missing _Accept Header_. What kind of _Accept Header_ should I give for request using android? Also, how do I add it. Or is it better to just remove that particular security? – dannyBoy Dec 29 '16 at 18:06
  • Take a look at [this](http://stackoverflow.com/a/15555952/6950238) answer of [Cyril Beschi](http://stackoverflow.com/users/2196599/cyril-beschi). – Andrii Omelchenko Dec 30 '16 at 09:29