Access a Web service using GET : Service « Network « Android






Access a Web service using GET

  

package app.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class Test extends Activity {
  ImageView img;

  private class BackgroundTask extends AsyncTask<String, Void, Bitmap> {
    protected Bitmap doInBackground(String... url) {
      // ---download an image---
      Bitmap bitmap = DownloadImage(url[0]);
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return bitmap;
    }

    protected void onPostExecute(Bitmap bitmap) {
      ImageView img = (ImageView) findViewById(R.id.img);
      img.setImageBitmap(bitmap);
    }
  }

  private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
      throw new IOException("Not an HTTP connection");
    try {
      HttpURLConnection httpConn = (HttpURLConnection) conn;
      httpConn.setAllowUserInteraction(false);
      httpConn.setInstanceFollowRedirects(true);
      httpConn.setRequestMethod("GET");
      httpConn.connect();
      response = httpConn.getResponseCode();
      if (response == HttpURLConnection.HTTP_OK) {
        in = httpConn.getInputStream();
      }
    } catch (Exception ex) {
      throw new IOException("Error connecting");
    }
    return in;
  }

  private Bitmap DownloadImage(String URL) {
    Bitmap bitmap = null;
    InputStream in = null;
    try {
      in = OpenHttpConnection(URL);
      bitmap = BitmapFactory.decodeStream(in);
      in.close();
    } catch (IOException e1) {
      Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG)
          .show();
      e1.printStackTrace();
    }
    return bitmap;
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btnOpen = (Button) findViewById(R.id.Button01);
    btnOpen.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        new BackgroundTask().execute("http://yourHost.com/1.jpg");
        String str = DownloadText("http://yourHost.com/a.rss");
        Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT)
            .show();
        
        WordDefinition("Apple");
      }
    });
  }

  private String DownloadText(String URL) {
    int BUFFER_SIZE = 2000;
    InputStream in = null;
    try {
      in = OpenHttpConnection(URL);
    } catch (IOException e1) {
      e1.printStackTrace();
      return "";
    }

    InputStreamReader isr = new InputStreamReader(in);
    int charRead;
    String str = "";
    char[] inputBuffer = new char[BUFFER_SIZE];
    try {
      while ((charRead = isr.read(inputBuffer)) > 0) {
        String readString = String.copyValueOf(inputBuffer, 0, charRead);
        str += readString;
        inputBuffer = new char[BUFFER_SIZE];
      }
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
      return "";
    }
    return str;
  }

  private void WordDefinition(String word) {
    InputStream in = null;
    try {
      in = OpenHttpConnection("http://services.aonaware.com/DictService/DictService.asmx/Define?word="+ word);
      Document doc = null;
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db;
      try {
        db = dbf.newDocumentBuilder();
        doc = db.parse(in);
      } catch (Exception e) {
        e.printStackTrace();
      }
      doc.getDocumentElement().normalize();
      // ---retrieve all the <Definition> nodes---
      NodeList definitionElements = doc.getElementsByTagName("Definition");
      String strDefinition = "";
      for (int i = 0; i < definitionElements.getLength(); i++) {
        Node itemNode = definitionElements.item(i);
        if (itemNode.getNodeType() == Node.ELEMENT_NODE) {
          Element definitionElement = (Element) itemNode;
          NodeList wordDefinitionElements = (definitionElement)
              .getElementsByTagName("WordDefinition");
          strDefinition = "";
          for (int j = 0; j < wordDefinitionElements.getLength(); j++) {
            Element wordDefinitionElement = (Element) wordDefinitionElements
                .item(j);
            NodeList textNodes = ((Node) wordDefinitionElement)
                .getChildNodes();
            strDefinition += ((Node) textNodes.item(0))
                .getNodeValue() + ". ";
          }
          Toast.makeText(getBaseContext(), strDefinition,
              Toast.LENGTH_SHORT).show();
        }
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<ImageView 
    android:id="@+id/img"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center" />    

<Button 
    android:text="Download Content" 
    android:id="@+id/Button01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" />

</LinearLayout>

   
    
  








Related examples in the same category

1.Map Service
2.Widget Service
3.Restful web service task
4.Search with Restful service
5.Post Restful service
6.Tracker Service
7.Weather web service
8.Alarm service
9.Get Running Services Info
10.Local service demo
11.extends Service
12.Service structure
13.Clock Back Service
14.Voice Recognition Service
15.is Connected by Context.CONNECTIVITY_SERVICE
16.BeatService extends Service and Thread
17.TimeoutService (beta). Here you can register a timeout.
18.Timeout Service
19.Screenshot Service