Saba Tyagi
Saba Tyagi

Reputation: 21

how to consume data in rest api that returns xml data in android

please can anybody tell how to consume rest API in android that returns xml data.there are so many example with JSON.but I need to response in xml format ...can anybody tell how to do that please help me thanks in advance.

Upvotes: 0

Views: 1427

Answers (3)

Saba Tyagi
Saba Tyagi

Reputation: 21

You can try something like this

private class CallAPI extends AsyncTask<String, String, String> {



    @Override
    protected String doInBackground(String... params) {
      String urlString=params[0]; // URL to call
      String schid="";
      String resultToDisplay = "";
      InputStream in = null;
      Result result = null ;


      // HTTP Get
      try {
        URL url = new URL(urlString);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        in = new BufferedInputStream(urlConnection.getInputStream());
        //resultToDisplay +="&" + URLEncoder.encode("data", "UTF-8") ; 
      } catch (Exception e ) {
        System.out.println(e.getMessage());
        return e.getMessage();
      }

       // Parse XML
       XmlPullParserFactory pullParserFactory;
       try {
            pullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = pullParserFactory.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); 
            parser.setInput(in, null);
            result = parseXML(parser);
       } catch (XmlPullParserException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }

       // Simple logic to determine if the email is dangerous, invalid, or valid
       if (result != null ) {
         if( result.hygieneResult.equals("Spam Trap")) {
           resultToDisplay = "Dangerous, please correct";
         }
         else if( Integer.parseInt(result.statusNbr) >= 300) {
           resultToDisplay = "Invalid, please re-enter";
         }
         else {
           resultToDisplay = "Thank you for your submission";
         }

       }
       else {
         resultToDisplay = "Exception Occured";
       }

       return resultToDisplay;

    }

    protected void onPostExecute(String schid) {
        if(schid == null) {
            schid = "THERE WAS AN ERROR";
        }
        Intent intent = new Intent(getApplicationContext(), ResultActivity.class); 
        intent.putExtra(EXTRA_MESSAGE, schid);
        startActivity(intent);
    }

    private Result parseXML( XmlPullParser parser ) throws XmlPullParserException, IOException {
      int eventType = parser.getEventType();
      Result result = new Result(); 

      while( eventType!= XmlPullParser.END_DOCUMENT) {
      String strid = null;
      switch(eventType)
      {
        case XmlPullParser.START_TAG:
            strid = parser.toString();
            //name=parser.getName();
          if( strid.equals("Error")) {
            System.out.println("Web API Error!");
          }
          else if ( strid.equals("StatusNbr")) {
            result.statusNbr = parser.nextText();
          }
          else if (strid.equals("HygieneResult")) {
            result.hygieneResult = parser.nextText();
          }
          break;
        case XmlPullParser.END_TAG:
          break;
        } // end switch

        eventType = parser.next();  
      } // end while
        return result;      
     }


} // end CallAPI

Now in your activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

// This is the method that is called when the submit button is clicked
public void verifyDetails(View view) {
    EditText schidEditText = (EditText) findViewById(R.id.sch_id);
    String schid = schidEditText.getText().toString();

    if( schid != null && !schid.isEmpty()) {
        String urlString = apiURL + "schid:" + schid.toString();
        //String urlString = apiURL + "LicenseInfo.RegisteredUser.UserID=" + strikeIronUserName + "&LicenseInfo.RegisteredUser.Password=" + strikeIronPassword + "&VerifyEmail.Email=" + email + "&VerifyEmail.Timeout=30";
      new CallAPI().execute(urlString); 
    }   




}



}

Upvotes: 2

sourabh devpura
sourabh devpura

Reputation: 625

You need to use DocumentBuilderFactory for Parsing XML using Java

You can find a good tutorial for this on that place XML and Java - Parsing XML using Java

Upvotes: 0

Related Questions