Home > Uncategorized > Call an #ASMX #webservice with #Android

Call an #ASMX #webservice with #Android

curso-android-net

This may not be the best way to call a Microsoft .NET ASMX webservice via Java for Android, but it seems to work OK for my needs. All you need to do, is call it asynchronously, and handle the data returned.

Here’s my class that I’m using to call the ASMX webservice;

package uk.org.regcheck.regcheck;

import android.os.AsyncTask;

import android.util.Log;

import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;



public class RegCheckAPI extends AsyncTask<String, String, String> {

    DataDownloadListener dataDownloadListener;
    public static interface DataDownloadListener {
        void dataDownloadedSuccessfully(String data);
        void dataDownloadFailed();
    }


    public void CheckUK(String RegistrationNumber,String username)
    {
        try {
            this.execute("https://www.regcheck.org.uk/api/reg.asmx/Check?" +
                    "&RegistrationNumber=" + URLEncoder.encode(RegistrationNumber, "utf-8") +
                    "&username=" + URLEncoder.encode(username, "utf-8"));
            Log.i(RegistrationNumber, username);
        }
        catch(UnsupportedEncodingException ex){
            Log.i("error",ex.getMessage());
        }
    }

    @Override
    protected String doInBackground(String... uri) {
        String responseString = "";
        try {
            URL url = new URL(uri[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            responseString = new String(readFully(in), "utf-8");
        }
        catch(IOException ex)
        {
            responseString = ex.toString();
        }
        return responseString;
    }

    private byte[] readFully(InputStream inputStream)
            throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = 0;
        while ((length = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, length);
        }
        return baos.toByteArray();
    }

    @Override
    protected void onPostExecute(String result) {
        if(result != null)
        {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(new InputSource(new StringReader(result)));
                NodeList nJson = doc.getElementsByTagName("vehicleJson");
                String strJson = nJson.item(0).getTextContent();
                JSONObject jObject = new JSONObject(strJson);
                String strDescription = jObject.getString("Description");
                dataDownloadListener.dataDownloadedSuccessfully(strDescription);
            }
            catch(Exception ex)
            {
                dataDownloadListener.dataDownloadFailed();
            }
        }
        else
            dataDownloadListener.dataDownloadFailed();

    }
}

 

Then my main activity is as follows;

package uk.org.regcheck.regcheck;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

TextView t = (TextView)findViewById(R.id.tbOutput);
t.setText(“Please wait…”);

RegCheckAPI api = new RegCheckAPI();
api.dataDownloadListener = (new RegCheckAPI.DataDownloadListener()
{
@SuppressWarnings(“unchecked”)
@Override
public void dataDownloadedSuccessfully(String data) {
TextView t = (TextView)findViewById(R.id.tbOutput);
t.setText(data);
}
@Override
public void dataDownloadFailed() {
// handler failure (e.g network not available etc.)
TextView t = (TextView)findViewById(R.id.tbOutput);
t.setText(“Failed”);
}
});
api.CheckUK(“{{valid UK plate}}”,”{{Your username here}}”);
}
}

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: