Android Tutorial - Network : URL

Using Intent to open a URL

 

package app.test;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

class MyBrowserActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.row);
    Uri url = getIntent().getData();
    WebView webView = (WebView) findViewById(R.id.WebView01);
    webView.setWebViewClient(new Callback());
    webView.loadUrl(url.toString());
  }
  private class Callback extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      return (false);
    }
  }
}
public class Test extends Activity {

  Button b1, b2, b3, b4, b5;
  int request_Code = 1;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    b1 = (Button) findViewById(R.id.btn_webbrowser);
    b1.setOnClickListener(new OnClickListener() {
      public void onClick(View arg0) {
        Intent i = new Intent("android.intent.action.VIEW");
        i.setData(Uri.parse("http://www.amazon.com"));
        startActivity(i);
      }
    });
    b2 = (Button) findViewById(R.id.btn_makecalls);
    b2.setOnClickListener(new OnClickListener() {
      public void onClick(View arg0) {
        Intent i = new Intent(android.content.Intent.ACTION_CALL, Uri.parse("tel:+651234567"));
        startActivity(i);
      }
    });
    b3 = (Button) findViewById(R.id.btn_showMap);
    b3.setOnClickListener(new OnClickListener() {
      public void onClick(View arg0) {
        Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri
            .parse("geo:37.827500,-122.481670"));
        startActivity(i);
      }
    });
    b4 = (Button) findViewById(R.id.btn_chooseContact);
    b4.setOnClickListener(new OnClickListener() {
      public void onClick(View arg0) {
        Intent i = new Intent(android.content.Intent.ACTION_PICK);
        i.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
        startActivityForResult(i, request_Code);
      }
    });

    b5 = (Button) findViewById(R.id.btn_launchMyBrowser);
    b5.setOnClickListener(new OnClickListener() {
      public void onClick(View arg0) {
        Intent i = new Intent("app.test.MyBrowser", Uri
            .parse("http://www.amazon.com"));
        i.addCategory("app.test.OtherApps");
        i.addCategory("app.test.SomeOtherApps");
        startActivity(i);
      }
    });
  }

  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
      if (resultCode == RESULT_OK) {
        Toast.makeText(this, data.getData().toString(),
            Toast.LENGTH_SHORT).show();
        Intent i = new Intent(android.content.Intent.ACTION_VIEW,
            Uri.parse(data.getData().toString()));
        startActivity(i);
      }
    }
  }
}

//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" >
<Button
    android:id="@+id/btn_webbrowser"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Web Browser" />    
<Button
    android:id="@+id/btn_makecalls"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Make Calls" />   
<Button
    android:id="@+id/btn_showMap"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Show Map" />    
<Button
    android:id="@+id/btn_chooseContact"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Choose Contact" />
<Button
    android:id="@+id/btn_launchMyBrowser"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Launch My Browser" />
    
</LinearLayout>
//row.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" >
<WebView 
    android:id="@+id/WebView01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" />
</LinearLayout>

    

Process xml document from a Url

 
package app.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
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.NodeList;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import java.util.Date;
import java.text.SimpleDateFormat;
import android.location.Location;

 class Quake {
  private Date date;
  private String details;
  private Location location;
  private double magnitude;
  private String link;

  public Date getDate() { return date; }
  public String getDetails() { return details; }
  public Location getLocation() { return location; }
  public double getMagnitude() { return magnitude; }
  public String getLink() { return link; }
  
  public Quake(Date _d, String _det, Location _loc, double _mag, String _link) {
    date = _d;
    details = _det;
    location = _loc;
    magnitude = _mag;
    link = _link;
  }

  @Override
  public String toString() {
    SimpleDateFormat sdf = new SimpleDateFormat("HH.mm");
    return sdf.format(date) + ": " + magnitude + " " + details;
  }

}
public class Test extends Activity {
  
  static final private int QUAKE_DIALOG = 1;
  static final private int MENU_UPDATE = Menu.FIRST;
  
  ListView earthquakeListView;
  
  ArrayAdapter<Quake> aa;
  ArrayList<Quake> earthquakes = new ArrayList<Quake>();
  
  Quake selectedQuake;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    earthquakeListView = (ListView)this.findViewById(R.id.earthquakeListView);
    earthquakeListView.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> _av, View _v, int _index, long _id) {
        selectedQuake = earthquakes.get(_index);
        showDialog(QUAKE_DIALOG);
      }
    });

    aa = new ArrayAdapter<Quake>(getApplicationContext(), android.R.layout.simple_list_item_1, earthquakes);
    earthquakeListView.setAdapter(aa);

    refreshEarthquakes();
  }
  private void refreshEarthquakes() {
    URL url;
    try {
      url = new URL("http://earthquake.usgs.gov/eqcenter/catalogs/1day-M2.5.xml");
           
      URLConnection connection = url.openConnection(); 
         
      HttpURLConnection httpConnection = (HttpURLConnection)connection; 
      int responseCode = httpConnection.getResponseCode(); 

      if (responseCode == HttpURLConnection.HTTP_OK) { 
        InputStream in = httpConnection.getInputStream(); 
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(in);      
        Element docEle = dom.getDocumentElement();
        earthquakes.clear();
        NodeList nl = docEle.getElementsByTagName("entry");
        if (nl != null && nl.getLength() > 0) {
          for (int i = 0 ; i < nl.getLength(); i++) {
            Element entry = (Element)nl.item(i);
            Element title = (Element)entry.getElementsByTagName("title").item(0);
            Element g = (Element)entry.getElementsByTagName("georss:point").item(0);
            Element when = (Element)entry.getElementsByTagName("updated").item(0);
            Element link = (Element)entry.getElementsByTagName("link").item(0);

            String details = title.getFirstChild().getNodeValue();
            String hostname = "http://earthquake.usgs.gov";
            String linkString = hostname + link.getAttribute("href");

            String point = g.getFirstChild().getNodeValue();
            String dt = when.getFirstChild().getNodeValue();  
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
            Date qdate = new GregorianCalendar(0,0,0).getTime();
            try {
              qdate = sdf.parse(dt);
            } catch (ParseException e) {
              e.printStackTrace();
            }

            String[] location = point.split(" ");
            Location l = new Location("dummyGPS");
            l.setLatitude(Double.parseDouble(location[0]));
            l.setLongitude(Double.parseDouble(location[1]));

            String magnitudeString = details.split(" ")[1];
            int end =  magnitudeString.length()-1;
            double magnitude = Double.parseDouble(magnitudeString.substring(0, end));
                
            details = details.split(",")[1].trim();
                
            Quake quake = new Quake(qdate, details, l, magnitude, linkString);
            addNewQuake(quake);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    finally {
    }
  }
  private void addNewQuake(Quake _quake) {
    earthquakes.add(_quake);
    aa.notifyDataSetChanged();
  }
    
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {      
    super.onCreateOptionsMenu(menu);
    menu.add(0, MENU_UPDATE, Menu.NONE, "update");
    return true;
  }
            
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
          
    switch (item.getItemId()) {
      case (MENU_UPDATE): {
        refreshEarthquakes();
        return true; 
      }
    } 
    return false;
  }
    
  @Override
  public Dialog onCreateDialog(int id) {
    switch(id) {
      case (QUAKE_DIALOG) :        
        LayoutInflater li = LayoutInflater.from(this);
        View quakeDetailsView = li.inflate(R.layout.row, null);
  
        AlertDialog.Builder quakeDialog = new AlertDialog.Builder(this);
        quakeDialog.setTitle("Quake Time");         
        quakeDialog.setView(quakeDetailsView);
        return quakeDialog.create();
    }
    return null;
  }
       
  @Override
  public void onPrepareDialog(int id, Dialog dialog) {
    switch(id) {
      case (QUAKE_DIALOG) :                  
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        String dateString = sdf.format(selectedQuake.getDate()); 
        String quakeText = "Mangitude " + selectedQuake.getMagnitude() + "\n" 
                           + selectedQuake.getDetails()  + "\n" + selectedQuake.getLink();          
          
        AlertDialog quakeDialog = (AlertDialog)dialog;
        quakeDialog.setTitle(dateString);
      
        TextView tv = (TextView)quakeDialog.findViewById(R.id.quakeDetailsTextView);
        if (tv != null)
          tv.setText(quakeText);

        break;
    }
  }
}

//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">
  <ListView
    android:id="@+id/earthquakeListView"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  />
</LinearLayout>

//row.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"
  android:padding="10sp">
  <TextView
    android:id="@+id/quakeDetailsTextView"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:textSize="14sp"
    android:autoLink="all"      
  />
</LinearLayout> 

Suggest Url Provider

 
package app.test;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

class SuggestUrlProvider extends ContentProvider 
{
    public static String AUTHORITY = "app.test.suggesturlprovider";
    final int SEARCH_SUGGEST = 0;
    private static final int SHORTCUT_REFRESH = 1;
    private static final UriMatcher sURIMatcher = buildUriMatcher();

    private static final String[] COLUMNS = {
            "_id",  // must include this column
            SearchManager.SUGGEST_COLUMN_TEXT_1,
            SearchManager.SUGGEST_COLUMN_TEXT_2,
            SearchManager.SUGGEST_COLUMN_INTENT_DATA,
            SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
            SearchManager.SUGGEST_COLUMN_SHORTCUT_ID
            };
    
    private static UriMatcher buildUriMatcher() {
        UriMatcher matcher =  new UriMatcher(UriMatcher.NO_MATCH);
        matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT, SHORTCUT_REFRESH);
        matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", SHORTCUT_REFRESH);
        return matcher;
    }

    @Override
    public boolean onCreate() {
        return true;
    }
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
      String query = selectionArgs[0];
        switch (sURIMatcher.match(uri)) {
            case SEARCH_SUGGEST:
              return getSuggestions(query);
            case SHORTCUT_REFRESH:
              return null;
            default:
                throw new IllegalArgumentException("Unknown URL " + uri);
        }
    }
    private Cursor getSuggestions(String query) 
    {
      if (query == null) return null;
      String word = getWord(query);
      if (word == null)
        return null;
        MatrixCursor cursor = new MatrixCursor(COLUMNS);
        cursor.addRow(createRow1(word));
        cursor.addRow(createRow2(word));
        return cursor;
    }
    private Object[] createRow1(String query)
    {
        return columnValuesOfQuery(query,
            "android.intent.action.VIEW",
            "http://www.thefreedictionary.com/" + query,
            "Look up in freedictionary.com for",
            query);
    }

    private Object[] createRow2(String query)
    {
        return columnValuesOfQuery(query,
            "android.intent.action.VIEW",
            "http://www.google.com/search?hl=en&source=hp&q=define%3A" + query,
            "Look up in google.com for",
            query);
    }
    private Object[] columnValuesOfQuery(String query,
        String intentAction,
        String url, 
        String text1, 
        String text2) 
    {
        return new String[] {
                query,     // _id
                text1,     // text1
                text2,     // text2
                url,       // intent_data (included when clicking on item)
                intentAction, //action
                SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT
        };
    }

    private Cursor refreshShortcut(String shortcutId, String[] projection) {
        return null;
    }

    public String getType(Uri uri) {
        switch (sURIMatcher.match(uri)) {
            case SEARCH_SUGGEST:
                return SearchManager.SUGGEST_MIME_TYPE;
            case SHORTCUT_REFRESH:
                return SearchManager.SHORTCUT_MIME_TYPE;
            default:
                throw new IllegalArgumentException("Unknown URL " + uri);
        }
    }

    public Uri insert(Uri uri, ContentValues values) {
        throw new UnsupportedOperationException();
    }

    public int delete(Uri uri, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException();
    }

    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException();
    }
    
    private String getWord(String query)
    {
      int dotIndex = query.indexOf('.'); 
      if (dotIndex < 0)
        return null;
      return query.substring(0,dotIndex);
    }
}

public class Test extends Activity 
{
  private final static String tag ="SearchActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Intent queryIntent = getIntent();
        final String queryAction = queryIntent.getAction();
        final String queryString = queryIntent.getStringExtra(SearchManager.QUERY);
        if (Intent.ACTION_SEARCH.equals(queryAction)) 
        {
          this.doSearchQuery(queryIntent);
        }
        else if (Intent.ACTION_VIEW.equals(queryAction)) 
        {
          this.doView(queryIntent);
        }
        return;
    }
    @Override
    public void onNewIntent(final Intent newIntent) 
    {
        super.onNewIntent(newIntent);
        final Intent queryIntent = newIntent;
        final String queryAction = queryIntent.getAction();
        final String queryString = queryIntent.getStringExtra(SearchManager.QUERY);
        if (Intent.ACTION_SEARCH.equals(queryAction)) {
          this.doSearchQuery(queryIntent);
        }else if (Intent.ACTION_VIEW.equals(queryAction)){
          this.doView(queryIntent);
        }
        return;
    }
    private void doSearchQuery(final Intent queryIntent) 
    {
        final String queryString = queryIntent.getStringExtra(SearchManager.QUERY);
        appendText("You are searching for:" + queryString);
    }
    private void appendText(String msg)
    {
        TextView tv = (TextView)this.findViewById(R.id.text1);
        tv.setText(tv.getText() + "\n" + msg);
    }
    private void doView(final Intent queryIntent) 
    {
        Uri uri = queryIntent.getData();
        String action = queryIntent.getAction();
        Intent i = new Intent(action);
        i.setData(uri);
        i.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
        startActivity(i);
        this.finish();
    } 

}

Showing android:autoLink property, which linkifies things like URLs and phone numbers found in the text.

 

        
import android.widget.TextView;
import android.content.Context;
import android.text.method.ScrollingMovementMethod;
import android.text.method.MovementMethod;
import android.text.Editable;
import android.util.AttributeSet;


 class LogTextBox extends TextView {
    public LogTextBox(Context context) {
        this(context, null);
    }

    public LogTextBox(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public LogTextBox(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected MovementMethod getDefaultMovementMethod() {
        return ScrollingMovementMethod.getInstance();
    }

    @Override
    public Editable getText() {
        return (Editable) super.getText();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, BufferType.EDITABLE);
    }
}






package com.example.android.apis.text;

import com.example.android.apis.R;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.widget.TextView;

public class Link extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.link);

        // text1 shows the android:autoLink property, which
        // automatically linkifies things like URLs and phone numbers
        // found in the text.  No java code is needed to make this
        // work.

        // text2 has links specified by putting <a> tags in the string
        // resource.  By default these links will appear but not
        // respond to user input.  To make them active, you need to
        // call setMovementMethod() on the TextView object.

        TextView t2 = (TextView) findViewById(R.id.text2);
        t2.setMovementMethod(LinkMovementMethod.getInstance());

        // text3 shows creating text with links from HTML in the Java
        // code, rather than from a string resource.  Note that for a
        // fixed string, using a (localizable) resource as shown above
        // is usually a better way to go; this example is intended to
        // illustrate how you might display text that came from a
        // dynamic source (eg, the network).

        TextView t3 = (TextView) findViewById(R.id.text3);
        t3.setText(
            Html.fromHtml(
                "<b>text3:</b>  Text with a " +
                "<a href=\"http://www.google.com\">link</a> " +
                "created in the Java source code using HTML."));
        t3.setMovementMethod(LinkMovementMethod.getInstance());

        // text4 illustrates constructing a styled string containing a
        // link without using HTML at all.  Again, for a fixed string
        // you should probably be using a string resource, not a
        // hardcoded value.

        SpannableString ss = new SpannableString(
            "text4: Click here to dial the phone.");

        ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 6,
                   Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new URLSpan("tel:4155551212"), 13, 17,
                   Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        TextView t4 = (TextView) findViewById(R.id.text4);
        t4.setText(ss);
        t4.setMovementMethod(LinkMovementMethod.getInstance());
    }
}


package com.example.android.apis.text;

import com.example.android.apis.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class LogTextBox1 extends Activity {
    
    private LogTextBox mText;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.log_text_box_1);
        
        mText = (LogTextBox) findViewById(R.id.text);
        
        Button addButton = (Button) findViewById(R.id.add);
        addButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                mText.append("This is a test\n");
            } });
    }
}



package com.example.android.apis.text;

import com.example.android.apis.R;

import android.app.Activity;
import android.os.Bundle;

public class Marquee extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.marquee);
    }
}



//layout/marqee.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent" 
    android:layout_height="match_parent">
    
    <Button
        android:layout_width="150dip" 
        android:layout_height="wrap_content"
        android:text="@string/marquee_default"
        android:singleLine="true"
        android:ellipsize="marquee"/>
        
    <Button
        android:layout_width="150dip" 
        android:layout_height="wrap_content"
        android:text="@string/marquee_once"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="1"/>
        
    <Button
        android:layout_width="150dip" 
        android:layout_height="wrap_content"
        android:text="@string/marquee_forever"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"/>  
           
</LinearLayout>

//layout/link.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">


  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/text1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:autoLink="all"
            android:text="@string/link_text_auto"
            />

  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/text2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@string/link_text_manual"
            />


  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/text3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/text4"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

</LinearLayout>

//layout/log_text_box_1.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/log_text_box_1_add_text"/>

    <com.example.android.apis.text.LogTextBox
        android:id="@+id/text"
        android:background="@drawable/box"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:scrollbars="vertical"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/log_text_box_1_do_nothing_text"/>

</LinearLayout> 

extends ArrayAdapter to create URL history

//package com.mediaportal.ampdroid.videoplayer;

import android.content.Context;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

public class URLHistory extends ArrayAdapter<URLHistory.HistoryItem> {
   private ArrayList<URLHistory.HistoryItem> spareCopy = new ArrayList<URLHistory.HistoryItem>();

   public URLHistory(Context context, int resource) {
      super(context, resource, new ArrayList<URLHistory.HistoryItem>());
   }

   public void update(String url) {
      for (HistoryItem h : spareCopy) {
         if (url.equals(h.url)) {
            h.count++;
            return;
         }
      }

      HistoryItem h = new HistoryItem(url);

      spareCopy.add(h);
      add(h); // duplicate due to moronic filtering
   }

   public void save(Writer out) throws JSONException, IOException {
      JSONStringer json = new JSONStringer().object();

      for (HistoryItem h : spareCopy) {
         h.emit(json);
      }

      out.write(json.endObject().toString());
   }

   public void load(String rawJSON) throws JSONException {
      JSONObject json = new JSONObject(rawJSON);

      for (Iterator i = json.keys(); i.hasNext();) {
         String key = i.next().toString();
         HistoryItem h = new HistoryItem(key, json.getInt(key));

         spareCopy.add(h);
         add(h);
      }
   }

   class HistoryItem {
      String url = null;
      int count = 1;

      HistoryItem(String url) {
         this.url = url;
      }

      HistoryItem(String url, int count) {
         this.url = url;
         this.count = count;
      }

      public String toString() {
         return (url);
      }

      void emit(JSONStringer json) throws JSONException {
         json.key(url).value(count);
      }
   } 

}

Used to compress URL using the bit.ly service.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


public class BitlyAndroid {
  /** Change this if you want to use j.mp instead. */
  public static BitlyService service = BitlyService.BITLY;

  private final String bitlyAuth;

  private HttpClient httpclient = null;

  /** Last response kept in case user gets exception and wants to see the response from bit.ly. */
  private BitlyReply lastResponse = null;

  public BitlyAndroid(String login, String apiKey) {
    bitlyAuth = "&format=json&login=" + login + "&apiKey=" + apiKey;
    httpclient = new DefaultHttpClient();
  }

  public String getShortUrl(String urlToShorten) throws Exception {
    BitlyReply reply = null;
    String httpResponse = null;
    httpResponse = getBitlyHttpResponseText(urlToShorten);
    reply = new BitlyReply(urlToShorten, httpResponse);
    lastResponse = reply;
    return reply.getShortUrl();
  }

  BitlyReply getBitlyReply(String urlToShorten) throws JSONException, IOException {
    String httpResponse = getBitlyHttpResponseText(urlToShorten);
    return new BitlyReply(urlToShorten, httpResponse);
  }

  private String getBitlyHttpResponseText(String urlToShorten) throws IOException {
    String uri = getBitlyUrl() + URLEncoder.encode(urlToShorten) + bitlyAuth;
    HttpGet httpGet = new HttpGet(uri);
    HttpResponse response = httpclient.execute(httpGet);
    String json = getText(response);
    return json;
  }

  private String getText(HttpResponse response) throws IOException {
    InputStream is = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line);
    }
    return sb.toString();
  }

  public BitlyReply getLastResponseFromBitLy() {
    return lastResponse;
  }

  private String getBitlyUrl() {
    return "http://api." + BitlyAndroid.service + "/shorten?version=2.0.1&longUrl=";
  }

  /** Represents a response from bit.ly. Mimics the structure of the JSON data. */
  public class BitlyReply {
    public String longUrl = "";

    public Integer errorCode;
    public String errorMessage;
    public String statusCode;
    public BitlyResult result;

    public BitlyReply(String longUrl, String jsonText) throws JSONException {
      this.longUrl = longUrl;
      JSONObject bitlyMessage = new JSONObject(jsonText);
      this.errorCode = bitlyMessage.getInt("errorCode");
      this.errorMessage = bitlyMessage.getString("errorMessage");
      this.statusCode = bitlyMessage.getString("statusCode");

      JSONObject results = bitlyMessage.getJSONObject("results");
      JSONObject urlResult = results.getJSONObject(longUrl);
      result = new BitlyResult(urlResult.getString("hash"), //
          urlResult.getString("shortCNAMEUrl"), //
          urlResult.getString("shortKeywordUrl"), //
          urlResult.getString("shortUrl"), //
          urlResult.getString("userHash"));//
    }

    public String getShortUrl() {
      return result.shortUrl;
    }

  }

  /** Result -object which contains the shortUrl. */
  public class BitlyResult {
    public String hash;
    public String shortCNAMEUrl;
    public String shortKeywordUrl;
    public String shortUrl;
    public String userHash;

    public BitlyResult(String hash, String shortCNAMEUrl, String shortKeywordUrl, String shortUrl, String userHash) {
      super();
      this.hash = hash;
      this.shortCNAMEUrl = shortCNAMEUrl;
      this.shortKeywordUrl = shortKeywordUrl;
      this.shortUrl = shortUrl;
      this.userHash = userHash;
    }
  }

  public enum BitlyService {
    BITLY {
      @Override
      public String toString() {
        return "bit.ly";
      }
    },
    JMP {
      @Override
      public String toString() {
        return "j.mp";
      }
    }
  }
 }

URL encode and decode

//package org.andlib.helpers;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAKeyGenParameterSpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


final  class StringCodec
{
  /**
   * 
   * @param original
   * @return null if fails
   */
  public static String urlencode(String original)
  {
    try
    {
      //return URLEncoder.encode(original, "utf-8");
      //fixed: to comply with RFC-3986
      return URLEncoder.encode(original, "utf-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }
    catch(UnsupportedEncodingException e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  
  /**
   * 
   * @param encoded
   * @return null if fails
   */
  public static String urldecode(String encoded)
  {
    try
    {
      return URLDecoder.decode(encoded, "utf-8");
    }
    catch(UnsupportedEncodingException e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  
 
  public static String hmacSha1Digest(String original, String key)
  {
    return hmacSha1Digest(original.getBytes(), key.getBytes());
  }
  

  public static String hmacSha1Digest(byte[] original, byte[] key)
  {
    try
    {
      Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(new SecretKeySpec(key, "HmacSHA1"));
      byte[] rawHmac = mac.doFinal(original);
      return new String(Base64Coder.encode(rawHmac));
    }
    catch (Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  

  public static String md5sum(byte[] original)
  {
    try
    {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(original, 0, original.length);
      StringBuffer md5sum = new StringBuffer(new BigInteger(1, md.digest()).toString(16));
      while(md5sum.length() < 32)
        md5sum.insert(0, "0");
      return md5sum.toString();
    }
    catch(NoSuchAlgorithmException e)
    {
      //Logger.e(e.toString());
    }
    return null;
  }
  
  /**
   * 
   * @param original
   * @return null if fails
   */
  public static String md5sum(String original)
  {
    return md5sum(original.getBytes());
  }

  public static byte[] aesEncrypt(byte[] original, byte[] key, byte[] iv)
  {
    if(key == null || (key.length != 16 && key.length != 24 && key.length != 32))
    {
    //  Logger.e("key's bit length is not 128/192/256");
      return null;
    }
    if(iv != null && iv.length != 16)
    {
    //  Logger.e("iv's bit length is not 16");
      return null;
    }

    try
    {
      SecretKeySpec keySpec = null;
      Cipher cipher = null;
      if(iv != null)
      {
        keySpec = new SecretKeySpec(key, "AES/CBC/PKCS7Padding");
        cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
      }
      else  //if(iv == null)
      {
        keySpec = new SecretKeySpec(key, "AES/ECB/PKCS7Padding");
        cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
      }

      return cipher.doFinal(original);
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }


  public static byte[] aesDecrypt(byte[] encrypted, byte[] key, byte[] iv)
  {
    if(key == null || (key.length != 16 && key.length != 24 && key.length != 32))
    {
    //  Logger.e("key's bit length is not 128/192/256");
      return null;
    }
    if(iv != null && iv.length != 16)
    {
    //  Logger.e("iv's bit length is not 16");
      return null;
    }

    try
    {
      SecretKeySpec keySpec = null;
      Cipher cipher = null;
      if(iv != null)
      {
        keySpec = new SecretKeySpec(key, "AES/CBC/PKCS7Padding");
        cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv));
      }
      else  //if(iv == null)
      {
        keySpec = new SecretKeySpec(key, "AES/ECB/PKCS7Padding");
        cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
      }

      return cipher.doFinal(encrypted);
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  

  public static KeyPair generateRsaKeyPair(int keySize, BigInteger publicExponent)
  {
    KeyPair keys = null;
    try
    {
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
      RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(keySize, publicExponent);
      keyGen.initialize(spec);
      keys = keyGen.generateKeyPair();
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return keys;
  }
  

  public static PublicKey generateRsaPublicKey(BigInteger modulus, BigInteger publicExponent)
  {
    try
    {
      return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  

  public static PrivateKey generateRsaPrivateKey(BigInteger modulus, BigInteger privateExponent)
  {
    try
    {
      return KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  

  public static byte[] rsaEncrypt(byte[] original, PublicKey key)
  {
    try
    {
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      cipher.init(Cipher.ENCRYPT_MODE, key);
      return cipher.doFinal(original);
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  

  public static byte[] rsaDecrypt(byte[] encrypted, PrivateKey key)
  {
    try
    {
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      cipher.init(Cipher.DECRYPT_MODE, key);
      return cipher.doFinal(encrypted);
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }


  public static String byteArrayToHexString(byte[] bytes)
  {
    StringBuffer buffer = new StringBuffer();
    for(int i=0; i<bytes.length; i++)
    {
      if(((int)bytes[i] & 0xff) < 0x10)
        buffer.append("0");
      buffer.append(Long.toString((int) bytes[i] & 0xff, 16));
    }
    return buffer.toString();
  }
  

  public static final byte[] hexStringToByteArray(String str)
  {
    int i = 0;
    byte[] results = new byte[str.length() / 2];
    for (int k = 0; k < str.length();)
    {
      results[i] = (byte)(Character.digit(str.charAt(k++), 16) << 4);
      results[i] += (byte)(Character.digit(str.charAt(k++), 16));
      i++;
    } 
    return results;
  }
}



class Base64Coder {

  //Mapping table from 6-bit nibbles to Base64 characters.
  private static char[]    map1 = new char[64];
  static {
     int i=0;
     for (char c='A'; c<='Z'; c++) map1[i++] = c;
     for (char c='a'; c<='z'; c++) map1[i++] = c;
     for (char c='0'; c<='9'; c++) map1[i++] = c;
     map1[i++] = '+'; map1[i++] = '/';
    }
  
  //Mapping table from Base64 characters to 6-bit nibbles.
  private static byte[]    map2 = new byte[128];
  static {
    for (int i=0; i<map2.length; i++) map2[i] = -1;
    for (int i=0; i<64; i++) map2[map1[i]] = (byte)i;
  }
  
 
  public static String encodeString (String s) {
    return new String(encode(s.getBytes()));
  }
  

  public static char[] encode (byte[] in) {
    return encode(in,in.length);
  }
  

  public static char[] encode (byte[] in, int iLen) {
    int oDataLen = (iLen*4+2)/3;       // output length without padding
    int oLen = ((iLen+2)/3)*4;         // output length including padding
    char[] out = new char[oLen];
    int ip = 0;
    int op = 0;
    while (ip < iLen) {
      int i0 = in[ip++] & 0xff;
      int i1 = ip < iLen ? in[ip++] & 0xff : 0;
      int i2 = ip < iLen ? in[ip++] & 0xff : 0;
      int o0 = i0 >>> 2;
      int o1 = ((i0 &   3) << 4) | (i1 >>> 4);
      int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
      int o3 = i2 & 0x3F;
      out[op++] = map1[o0];
      out[op++] = map1[o1];
      out[op] = op < oDataLen ? map1[o2] : '='; op++;
      out[op] = op < oDataLen ? map1[o3] : '='; op++; }
    return out; 
  }
  
  
  public static String decodeString (String s) {
    return new String(decode(s)); 
  }
  

  public static byte[] decode (String s) {
    return decode(s.toCharArray()); 
  }
  
 
  public static byte[] decode (char[] in) {
    int iLen = in.length;
    if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");
    while (iLen > 0 && in[iLen-1] == '=') iLen--;
    int oLen = (iLen*3) / 4;
    byte[] out = new byte[oLen];
    int ip = 0;
    int op = 0;
    while (ip < iLen) {
      int i0 = in[ip++];
      int i1 = in[ip++];
      int i2 = ip < iLen ? in[ip++] : 'A';
      int i3 = ip < iLen ? in[ip++] : 'A';
      if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
        throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
      int b0 = map2[i0];
      int b1 = map2[i1];
      int b2 = map2[i2];
      int b3 = map2[i3];
      if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
        throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
      int o0 = ( b0       <<2) | (b1>>>4);
      int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
      int o2 = ((b2 &   3)<<6) |  b3;
      out[op++] = (byte)o0;
      if (op<oLen) out[op++] = (byte)o1;
      if (op<oLen) out[op++] = (byte)o2;
    }
    return out;
  }
  
  //Dummy constructor.
  private Base64Coder() {}

} // end class Base64Coder
Is valid URL
//package org.peterbaldwin.client.android.tinyurl;

import java.net.MalformedURLException;
import java.net.URL;

class Util {
    private Util() {
    }

    public static boolean isValidUrl(String url) {
        try {
            new URL(url);
            return true;
        } catch (MalformedURLException e) {
            return false;
        }
    }
}

Download from URLConnection

 

//package org.mimp.newimp;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLConnection;

class NetUtil {
    public static byte[] download(URLConnection cnx) {
        byte[] dat = null;
        try {
            InputStream is = cnx.getInputStream();
            int len = cnx.getContentLength();
            if (len < 0) {
                ByteArrayOutputStream bao = new ByteArrayOutputStream();
                byte[] buf = new byte[4096];
                for (;;) {
                    int nb = is.read(buf);
                    if (nb <= 0)
                        break;
                    bao.write(buf, 0, nb);
                }
                dat = bao.toByteArray();
                bao.close();
            }
            else {
                dat = new byte[len];
                int i = 0;
                while (i < len) {
                    int n = is.read(dat, i, len - i);
                    if (n <= 0)
                        break;
                    i += n;
                }
            }
            is.close();
        }
        catch (Exception ex) {
        }
        return dat;
    }
}

Request from an URL

 
//package com.ho9ho9.tepcometer.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;


class HttpUtils {
  
  /** HTTP_METHOD_GET. */
  private static final String HTTP_METHOD_GET = "GET";
  private static final String TAG_NAME = "TepcoMetterWidgetService";
  
  public static String get(String url) {
    Log.d(TAG_NAME, "url:" + url);
    return request(url, HTTP_METHOD_GET);
  }
  private static String request(String url, String method) {
    String result = null;
    HttpURLConnection con = null;
    BufferedReader reader = null;
    try {
      con = (HttpURLConnection) new URL(url).openConnection();
      con.setRequestMethod(method);
      reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line);
      }
      result = sb.toString();
    } catch (MalformedURLException e) {
      Log.e(TAG_NAME, e.getMessage(), e);
    } catch (IOException e) {
      Log.e(TAG_NAME, e.getMessage(), e);
    } finally {
      if (con != null) {
        con.disconnect();
      }
      try {
        if (reader != null) {
          reader.close();
        }
      } catch (IOException e) {
      }
    }
    Log.d(TAG_NAME, "response:" + result);
    return result;
  }

}

Get Url From Img Tag

 
    
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Collection;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main{
    public static String getUrlFromImgTag(String imgTag)
    {
      String url = null;
      
    Pattern p = Pattern.compile("src='[^']*'", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(imgTag);
    if (m.find())
    {
      url = imgTag.substring(m.start() + 5, m.end() - 1);
    }
    
    return url;
   }
}

Returns the contents of the given URL as an array of strings

//package android.skireport;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.SharedPreferences;

public class HttpUtils
{
  public final static String LOC_SERVER = "http://bettykrocks.com/skireport";

  static HttpClient getHttpClient()
  {
    return new DefaultHttpClient();
  }
  
  /**
   * Returns the contents of the given URL as an array of strings
   */
  public static String[] fetchUrl(String url) 
    throws ClientProtocolException, IOException
  {
    ArrayList<String> lines = new ArrayList<String>();
    
    url = url.replace(" ", "%20");
    
    HttpResponse resp = getHttpClient().execute(new HttpGet(url));
    if( resp.getStatusLine().getStatusCode() == 200 )
    {
      InputStreamReader ir = 
        new InputStreamReader(resp.getEntity().getContent());
      BufferedReader r = new BufferedReader(ir);
      
      String line;
      while( (line = r.readLine()) != null )
        lines.add(line);
    }
    else
    {
      throw new IOException("LocationFinder: unable to get URL[" + url +"]");
    }
    
    return lines.toArray(new String[lines.size()]);
  }
  
  /**
   * Returns the server to retrieve location data from.
   * @return
   */
  public static String getLocationServer(SharedPreferences pref)
  {
    return pref.getString("location_server", LOC_SERVER);
  }
}

Read from a URL

//package de.avanux.android.livetracker2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class HttpUtil {

  // lat=50.2911 lon=8.9842

  private final static String TAG = "LiveTracker:HttpUtil";

  public static String get(String url) throws ClientProtocolException, IOException {
    Log.d(TAG, "HTTP GET " + url);
    HttpGet method = new HttpGet(url);
    HttpResponse response = executeMethod(method);
    return getResponseAsString(response);
  }

  public static String post(String url, Map<String, String> httpParameters) throws ClientProtocolException, IOException {
    Log.d(TAG, "HTTP POST " + url);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(httpParameters.size());
    Set<String> httpParameterKeys = httpParameters.keySet();
    for (String httpParameterKey : httpParameterKeys) {
      nameValuePairs.add(new BasicNameValuePair(httpParameterKey, httpParameters.get(httpParameterKey)));
    }

    HttpPost method = new HttpPost(url);
    method.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = executeMethod(method);
    return getResponseAsString(response);
  }

  private static HttpResponse executeMethod(HttpRequestBase method) throws ClientProtocolException, IOException {
    HttpResponse response = null;
    HttpClient client = new DefaultHttpClient();
    response = client.execute(method);
    Log.d(TAG, "executeMethod=" + response.getStatusLine());
    return response;
  }

  private static String getResponseAsString(HttpResponse response) throws IllegalStateException, IOException {
    String content = null;
    InputStream stream = null;
    try {
      if (response != null) {
        stream = response.getEntity().getContent();
        InputStreamReader reader = new InputStreamReader(stream);
        BufferedReader buffer = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String cur;
        while ((cur = buffer.readLine()) != null) {
          sb.append(cur + "\n");
        }
        content = sb.toString();
      }
    } finally {
      if (stream != null) {
        stream.close();
      }
    }
    return content;
  }

Pull the raw text content of the given URL.

 
//package com.MetroMinder.Utilities;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class UrlHelpers {
  
  /* {@link StatusLine} HTTP status code when no server error has occurred.  */
    private static final int HTTP_STATUS_OK = 200;
    
    /* Shared buffer used by {@link #getUrlContent(String)} when reading results
     * from an API request. */
    private static byte[] sBuffer = new byte[512];

    /* Thrown when there were problems contacting the remote API server, either
     * because of a network error, or the server returned a bad status code. */
    public static class ApiException extends Exception
    {        
      public ApiException(String detailMessage, Throwable throwable)
      {
            super(detailMessage, throwable);
        }

        public ApiException(String detailMessage)
        {
            super(detailMessage);
        }        
    }
    

    /* Thrown when there were problems parsing the response to an API call,
     * either because the response was empty, or it was malformed.  */
    public static class ParseException extends Exception 
    {      
        public ParseException(String detailMessage, Throwable throwable) 
        {
            super(detailMessage, throwable);
        }        
    }

    /* Read and return the full HTML content of the URL requested
     * @param urlToFetch 
     * @return Exact content of page.
     * @throws ApiException If any connection or server error occurs.
     * @throws ParseException If there are problems parsing the response. */
    public static String getPageContent(String urlToFetch) throws ApiException, ParseException 
    {
      return getUrlContent(String.format(urlToFetch));
    }
    

    /* Pull the raw text content of the given URL. This call blocks until the
     * operation has completed, and is synchronized because it uses a shared
     * buffer {@link #sBuffer}.
     * @param url The exact URL to request.
     * @return The raw content returned by the server.
     * @throws ApiException If any connection or server error occurs. */
    protected static synchronized String getUrlContent(String url) throws ApiException 
    {
        // Create client and set our specific user-agent string
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        request.setHeader("User-Agent", "MetroMinder (Linux; Android)");

        try
        {
            HttpResponse response = client.execute(request);

            // Check if server response is valid
            StatusLine status = response.getStatusLine();
            
            if (status.getStatusCode() != HTTP_STATUS_OK) 
            {
                throw new ApiException("Invalid response from server: " + status.toString());
            }

            // Pull content stream from response
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();

            ByteArrayOutputStream content = new ByteArrayOutputStream();

            // Read response into a buffered stream
            int readBytes = 0;
            while ((readBytes = inputStream.read(sBuffer)) != -1) 
            {
                content.write(sBuffer, 0, readBytes);
            }

            // Return result from buffered stream
            return new String(content.toByteArray());
        } 
        catch (IOException e) 
        {
            throw new ApiException("Problem communicating with API", e);
        }
      
    }

}

Get Video from URL

 

//package androtv.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

class SiteClientUtil {

  private SiteClientUtil() {
  }

  public static String getSiteUrl() {
    return "http://json.protv.md/featured?ctr=_" + new Date().getTime();
  }

  public static String getNews() {
    HttpClient httpclient = new DefaultHttpClient();
    // TODO: format url wit current date
    String url = getSiteUrl();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response;
    String result = null;

    try {
      response = httpclient.execute(httpget);

      // Get hold of the response entity
      HttpEntity entity = response.getEntity();
      // If the response does not enclose an entity, there is no need
      // to worry about connection release

      if (entity != null) {
        // A Simple Response Read
        InputStream instream = entity.getContent();
        result = convertStreamToString(instream);

        // Closing the input stream will trigger connection release
        instream.close();
      }
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return result;

  }

  public static Bitmap getImage(String url) throws MalformedURLException,
      IOException {

    Bitmap bitmap = null;
    InputStream in = null;
    try {
      in = OpenHttpConnection(url);
      bitmap = BitmapFactory.decodeStream(in, null,
          new BitmapFactory.Options());
      in.close();
    } catch (IOException e1) {
    }
    return bitmap;
  }

  public static String getVideoUrl(String url) throws IOException {
    InputStream stream = OpenHttpConnection(url);
    String html = convertStreamToString(stream);
    int startIndex = html.indexOf("$('#video').flash(");

    if (startIndex == -1) {
      return null;
    }

    startIndex = html.indexOf("file:", startIndex);
    int endIndex = html.indexOf(",", startIndex);

    if (endIndex == -1) {
      return null;
    }

    return html.substring(startIndex + 5, endIndex);
  }

  private static InputStream OpenHttpConnection(String url)
      throws IOException {
    InputStream inputStream = null;
    URL _url = new URL(url);
    URLConnection conn = _url.openConnection();

    try {
      HttpURLConnection httpConn = (HttpURLConnection) conn;
      httpConn.setRequestMethod("GET");
      httpConn.connect();

      if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        inputStream = httpConn.getInputStream();
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return inputStream;
  }

  private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the
     * BufferedReader.readLine() method. We iterate until the BufferedReader
     * return null which means there's no more data to read. Each line will
     * appended to a StringBuilder and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is),
        8192);
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return sb.toString();
  }

}

Gets data from URL

 
//package com.sabdroid.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

public class HttpUtil
{
    private static HttpUtil _instance;
    private static DefaultHttpClient httpClient = new DefaultHttpClient();

    private HttpUtil()
    {
        HttpParams params = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 60000);
        HttpConnectionParams.setSoTimeout(params, 60000);
    }

    public static HttpUtil instance()
    {
        if (_instance == null)
            _instance = new HttpUtil();

        return _instance;
    }

    /**
     * Gets data from URL
     * throws {@link RuntimeException} If anything goes wrong
     * @throws ServerConnectinoException 
     */
    public String getData(String url) throws ServerConnectinoException
    {
        try
        {
            HttpGet request = new HttpGet(url);

            HttpResponse response = httpClient.execute(request);

            int status = response.getStatusLine().getStatusCode();

            if (status != HttpStatus.SC_OK)
            {
                throw new ServerConnectinoException("Connection Error: " + response.getStatusLine().getReasonPhrase());
            }
            else
            {
                InputStream content = response.getEntity().getContent();

                return inputStreamAsString(content);
            }
        }
        catch (ServerConnectinoException e)
        {
            throw new ServerConnectinoException(e.getMessage());
        }
        catch (IOException e)
        {
            throw new ServerConnectinoException("Connection timeout!");
        }
        catch (Throwable e)
        {
            Log.w("HTTP", "Failed to connect to server", e);
            throw new RuntimeException(e);
        }
    }

    public static String inputStreamAsString(InputStream stream) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(stream));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = br.readLine()) != null)
        {
            sb.append(line + "\n");
        }

        br.close();
        String result = sb.toString();
        stream.close();
        return result.substring(0, result.length() - 1);
    }

    public class ServerConnectinoException extends Exception
    {
        private static final long serialVersionUID = -7812290125811215338L;

        public ServerConnectinoException(String message)
        {
            super(message);
        }
    }
}

get Url Response

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

class IOUtils {

  private static final String LOG_TAG = "IOUtils";
  public static final String PREFS_FILE = "javaeye.prefs";

  public static String getUrlResponse(String url) {
    try {
      HttpGet get = new HttpGet(url);
      HttpClient client = new DefaultHttpClient();
      HttpResponse response = client.execute(get);
      HttpEntity entity = response.getEntity();
      return convertStreamToString(entity.getContent());
    } catch (Exception e) {
    }
    return null;
  }

  private static String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is),8 * 1024);
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (IOException e) {
    } finally {
      try {
        is.close();
      } catch (IOException e) {
      }
    }
    return sb.toString();
  }

}

URL Encode Utils

 
//package weibo4android.util;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.BitSet;
/**
 * @author yuanming
 * 
 */
public class URLEncodeUtils {

  static BitSet dontNeedEncoding;

  static {

   

    dontNeedEncoding = new BitSet(256);
    int i;
    for (i = 'a'; i <= 'z'; i++) {
      dontNeedEncoding.set(i);
    }
    for (i = 'A'; i <= 'Z'; i++) {
      dontNeedEncoding.set(i);
    }
    for (i = '0'; i <= '9'; i++) {
      dontNeedEncoding.set(i);
    }
    dontNeedEncoding.set(' '); /*
                   * encoding a space to a + is done in the
                   * encode() method
                   */
    dontNeedEncoding.set('-');
    dontNeedEncoding.set('_');
    dontNeedEncoding.set('.');
    dontNeedEncoding.set('*');

    dontNeedEncoding.set('+');
    dontNeedEncoding.set('%');

  }

  /**
   * ?????????urlencode?
   * 
   * @param str
   * @return
   */
  public static final boolean isURLEncoded(String str) {
    if (str==null &&"".equals(str)) {
      return false;
    }
    char[] chars = str.toCharArray();
    boolean containsPercent = false;
    for (char c : chars) {
      if (Character.isWhitespace(c)) {
        return false;
      }
      if (!dontNeedEncoding.get(c)) {
        return false;
      }
      if(c == '%'){
        containsPercent = true;
      }
    }
    if(!containsPercent){
      return false;
    }
    return true;
  }

  public static final String encodeURL(String str) {
    try {
      return URLEncoder.encode(str, "utf-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }
  public static final String decodeURL(String str) {
    try {
      return URLDecoder.decode(str, "utf-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }
  
}

Downloads a file given URL to specified destination

//package net.vexelon.bgrates;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;


public class Utils {
  
  /**
   * Downloads a file given URL to specified destination
   * @param url
   * @param destFile
   * @return
   */
  //public static boolean downloadFile(Context context, String url, String destFile) {
  public static boolean downloadFile(Context context, String url, File destFile) {
    //Log.v(TAG, "@downloadFile()");
    //Log.d(TAG, "Downloading " + url);
    
    boolean ret = false;
    
    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    InputStream is = null;
    
    try {
      URL myUrl = new URL(url);
      URLConnection connection = myUrl.openConnection();
      
      is = connection.getInputStream();
      bis = new BufferedInputStream(is);
      ByteArrayBuffer baf = new ByteArrayBuffer(1024);
      
      int n = 0;
      while( (n = bis.read()) != -1 )
        baf.append((byte) n);
      
      // save to internal storage
      //Log.v(TAG, "Saving downloaded file ...");
      fos = new FileOutputStream(destFile); 
        //context.openFileOutput(destFile, context.MODE_PRIVATE);
      fos.write(baf.toByteArray());
      fos.close();
      //Log.v(TAG, "File saved successfully.");
      
      ret = true;
    }
    catch(Exception e) {
      //Log.e(TAG, "Error while downloading and saving file !", e);
    }
    finally {
      try {
        if ( fos != null ) fos.close();
      } catch( IOException e ) {}
      try {
        if ( bis != null ) bis.close();
      } catch( IOException e ) {}
      try {
        if ( is != null ) is.close();
      } catch( IOException e ) {}
    }
    
    return ret;
  }

}

get Host From Url

 
//package com.retain;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.Date;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * @author Nazmul Idris
 * @version 1.0
 * @since Jul 8, 2008, 2:35:39 PM
 */
class AppUtils {

  /**
   * 127.0.0.1 in the emulator points back to itself. Use this if you want to
   * access your host OS
   */
  public static String EmulatorLocalhost = "10.0.2.2";

  static public String getHostFromUrl(String url) {
    try {
      URI uri = new URI(url);
      String host = uri.getHost();
      if (host == null)
        return null;

      host = host.replaceAll("^www\\.", "");

      int i = host.lastIndexOf('.');
      if (i >= 0) {
        int j = host.lastIndexOf('.', i - 1);
        if (j >= 0)
          host = host.substring(j + 1, host.length());
      }
      return host;
    } catch (URISyntaxException urie) {
      Log.e("getHostFromUrl", urie.getMessage());
    }

    return url;

  }

}// end class AppUtils

encode Url

 


//package com.renren.api.connect.android;

import android.os.Bundle;


 class Util {

  public static String encodeUrl(Bundle parameters) {
    if (parameters == null)
      return "";
    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (String key : parameters.keySet()) {
      if (first)
        first = false;
      else
        sb.append("&");
      sb.append(key + "=" + parameters.getString(key));
    }
    return sb.toString();
  }

}

decode Url

//package com.renren.api.connect.android;
import java.net.URLDecoder;

import android.os.Bundle;

class Util {
  public static Bundle decodeUrl(String s) {
    Bundle params = new Bundle();
    if (s != null) {
      params.putString("url", s);
      String array[] = s.split("&");
      for (String parameter : array) {
        String v[] = parameter.split("=");
        if (v.length > 1)
          params.putString(v[0], URLDecoder.decode(v[1]));
      }
    }
    return params;
  }
}

Convert a byte array to a URL encoded string

//package atorrentapi;


class Main {

  public static String byteArrayToURLString(byte in[]) {
    byte ch = 0x00;
    int i = 0;
    if (in == null || in.length <= 0)
      return null;

    String pseudo[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
        "A", "B", "C", "D", "E", "F" };
    StringBuffer out = new StringBuffer(in.length * 2);

    while (i < in.length) {
      // First check to see if we need ASCII or HEX
      if ((in[i] >= '0' && in[i] <= '9')
          || (in[i] >= 'a' && in[i] <= 'z')
          || (in[i] >= 'A' && in[i] <= 'Z') || in[i] == '$'
          || in[i] == '-' || in[i] == '_' || in[i] == '.'
          || in[i] == '!') {
        out.append((char) in[i]);
        i++;
      } else {
        out.append('%');
        ch = (byte) (in[i] & 0xF0); // Strip off high nibble
        ch = (byte) (ch >>> 4); // shift the bits down
        ch = (byte) (ch & 0x0F); // must do this is high order bit is
        // on!
        out.append(pseudo[(int) ch]); // convert the nibble to a
        // String Character
        ch = (byte) (in[i] & 0x0F); // Strip off low nibble
        out.append(pseudo[(int) ch]); // convert the nibble to a
        // String Character
        i++;
      }
    }

    String rslt = new String(out);

    return rslt;

  }
}

get Url content with max retries

 
import java.io.IOException;
import java.net.SocketException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

class Main {
  private static HttpParams defaultHttpParams = new BasicHttpParams();
  
  public static String getUrl(String url, int maxRetries) throws IOException {
    String result = null;
    int retries = 0;
    DefaultHttpClient httpclient = new DefaultHttpClient(defaultHttpParams);
    httpclient.setCookieStore(null);
    HttpGet httpget = new HttpGet(url);
    while (retries <= maxRetries && result == null) {
      try {
        retries++;
        HttpEntity entity = httpclient.execute(httpget).getEntity();

        if (entity != null) {
          result = EntityUtils.toString(entity).trim();
        }
      } catch (SocketException se) {
        if (retries > maxRetries) {
          throw se;
        } else {
          //Log.v(TAG, "SocketException, retrying " + retries);
        }
      }
    }

    return result;
  }
}

get Url By Post

 
import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.util.Log;

class Main {
  private static HttpParams defaultHttpParams = new BasicHttpParams();
  private static final String UTF8 = "UTF-8";

  public static String getUrlByPost(String url, Map<String, String> params, Map<String, String> headers,
      int maxRetries) throws IOException {
    String result = null;
    int retries = 0;
    DefaultHttpClient httpclient = new DefaultHttpClient(defaultHttpParams);
    httpclient.setCookieStore(null);

    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    if (params != null) {
      Set<Entry<String, String>> paramsSet = params.entrySet();
      for (Entry<String, String> entry : paramsSet) {
        formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
      }
    }

    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formParams, UTF8);
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(postEntity);

    if (headers != null) {
      Set<Entry<String, String>> headersSet = headers.entrySet();
      for (Entry<String, String> entry : headersSet) {
        httppost.setHeader(entry.getKey(), entry.getValue());
      }
    }

    while (retries < maxRetries && result == null) {
      try {
        retries++;
        HttpEntity responseEntity = httpclient.execute(httppost).getEntity();
        if (responseEntity != null) {
          result = EntityUtils.toString(responseEntity).trim();
        }
      } catch (SocketException se) {
        if (retries > maxRetries) {
          throw se;
        } else {
        //  Log.v(TAG, "SocketException, retrying " + retries, se);
        }
      }
    }

    return result;
  }
}

Take a base url and a {@link Map} of parameters to build a valid url

import java.util.Map;

class Main {
  
  public static String buildUrl(String baseUrl, Map<String, Object> parameters) {
    StringBuilder strBuilderUrl = new StringBuilder(baseUrl);
    if (parameters != null && parameters.size() > 0) {
      int i = 0;
      for (Map.Entry<String, Object> entry : parameters.entrySet()) {
        if (i == 0) {
          strBuilderUrl.append('?');
        } else {
          strBuilderUrl.append('&');
        }
        strBuilderUrl.append(entry.getKey());
        strBuilderUrl.append('=');
        strBuilderUrl.append(entry.getValue());
        i++;
      }

    }
    return strBuilderUrl.toString();
  }
}