Recipe Using an Http Get

Besides launching a browser or using the Webview widget to include a WebKit-based browser control in an activity, developers might also want to create native Internet-based applications. This means the application relies on only the raw data from the Internet, such as images, media files, and XML data. Just the data of relevance can be loaded.This is important for creating social networking applications.Two packages are useful in Android to handle network communication: java.net and android.net.

In this recipe, the HTTP GET is used to retrieve XML or JSON data (see http:// www.json.org/ for an overview). In particular, the Google search Representational State Transfer (REST) Application Programming Interface (API) is demonstrated, and the following query is used:

http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=

More information on Google Asynchronous Javascript And XML (AJAX) search can be found at http://code.google.com/apis/ajaxsearch/.

To search any topic, the topic just needs to be appended to the query. For example, to search information on the National Basketball Association (NBA), the following query returns JSON data:

http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=NBA

The activity needs Internet permission to run. So, the following should be added to the AndroidManifest XML file:

<uses-permission android:name="android.permission.INTERNET"/>

The main layout is shown in Listing 8.5. It has three views: EditText for user input of the search topic, Button to trigger the search, and TextView to display the search result.

Listing 8.5 res/layout/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" >

<EditText android:id="@+id/editText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true" />

<Button android:id="@+id/submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Search" />

<TextView android:id="@+id/display" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello" android:textSize="18dp" />

</LinearLayout>

The main activity is shown in Listing 8.6. It initiates the three layout elements in onCreate(). Inside the OnClickListener for the button, it calls the SearchRequest() .This composes the search item using the Google REST API URL and then initiates an URL class instance.The URL class instance is then used to get an HttpURLConnection instance.

The HttpURLConnection instance can retrieve the status of the connection.When the HttpURLConnection returns a result code of http_OK, it means the whole HTTP transaction went through.Then, the JSON data returned from the HTTP transaction can be dumped into a string.This is done using an InputStreamReader passed to a BufferReader to read the data and create a String instance.After the result from HTTP is obtained, it uses another function ProcessResponse() to parse the JSON data.The detailed mechanism used requires an understanding of the incoming JSON data structure. In this case, the Google REST API provides all the result data under the results JSONArray. Figure 8.1 shows a screenshot of the search result for NBA.

Listing 8.6 src/com/cookbook/internet/search/GoogleSearch.java package com.cookbook.internet.search;

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 java.security.NoSuchAlgorithmException;

import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;

import android.app.Activity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

public class GoogleSearch extends Activity {

/** Called when the activity is first created. */ TextView tvl; EditText edl; Button btl; static String url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";

^Override public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState); setContentView(R.layout.main);

tv1 = (TextView) this.findViewByld(R.id.display); ed1 = (EditText) this.findViewByld(R.id.editText); bt1 = (Button) this.findViewByld(R.id.submit);

bt1.setOnClickListener(new OnClickListener() { public void onClick(View view) {

ProcessResponse(

SearchRequest(ed1.getText().toString())); } catch(Exception e) {

Log.v("Exception google search",

"Exception:"+e.getMessage());

public String SearchRequest(String searchString)

throws MalformedURLException, IOException { String newFeed=url+searchString; StringBuilder response = new StringBuilder(); Log.v("gsearch","gsearch url:"+newFeed); URL url = new URL(newFeed);

HttpURLConnection httpconn

= (HttpURLConnection) url.openConnection();

if(httpconn.getResponseCode()==HttpURLConnection.HTTP_OK) { BufferedReader input = new BufferedReader(

new InputStreamReader(httpconn.getInputStream()), 8192); String strLine = null;

while ((strLine = input.readLine()) != null) { response.append(strLine);

input.close();

return response.toString();

public void ProcessResponse(String resp) throws IllegalStateException, IOException, JSONException, NoSuchAlgorithmException { StringBuilder sb = new StringBuilder(); Log.v("gsearch","gsearch result:"+resp); JSONObject mResponseObject = new JSONObject(resp); JSONObject responObject

= mResponseObject.getJSONObject("responseData"); JSONArray array = responObject.getJSONArray("results"); Log.v("gsearch","number of resultst:"+array.length()); for(int i = 0; i<array.length(); i++) {

Log.v("result",i+"] "+array.get(i).toString());

String title = array.getJSONObject(i).getString("title");

String urllink = array.getJSONObject(i)

•getString("visibleUrl");

sb.append(title); sb.append("\n"); sb.append(urllink); sb.append("\n");

tv1.setText(sb.toString());

Google Search

<b>NBA</b>.com: PLAYOFFS 2010 www.nba.com

<b>NBA</b> - National Basketball Association Teams, Scores, Stats, News <b>...</b> espn.go.com

National Basketball Association -Wikipedia, the free encyclopedia en.wiki pedla.org

<b>NBA</b> on Yahoo! Sports - News, Scores, Standings, Rumors, Fantasy Games sports.yahoo.com

Figure 8.1 The search result from the Google REST API query.

Recipe: Using HTTP POST

Sometimes, raw binary data needs to be retrieved from the Internet such as an image, video, or audio file. This can be achieved using the HTTP POST protocol by using the setRequestMethod(), such as: httpconn.setRequestMethod(POST);

Accessing data through the Internet can be time-consuming and unpredictable. Therefore, a separate thread should be spawned anytime network data is required.

In addition to the methods shown in Chapter 3,"Threads, Services, Receivers, and Alerts," there is a built-in Android class called AsyncTask that allows background operations to be performed and publishes results on the UI thread without needing to manipulate threads or handlers. So, the POST method can be implemented asynchronously with the following code:

private class mygoogleSearch extends AsyncTask<String, Integer, String> { protected String doInBackground(String... searchKey) { String key = searchKey[0]; try {

return SearchRequest(key); } catch(Exception e) {

Log.v("Exception google search",

"Exception:"+e.getMessage()); return "";

protected void onPostExecute(String result) { try {

ProcessResponse(result); } catch(Exception e) {

Log.v("Exception google search",

"Exception:"+e.getMessage());

This excerpt can be added to the end of the GoogleSearch.java activity in Listing 8.6. It provides the same result with one additional change to the code inside the button OnClickListener to:

new mygoogleSearch().execute(ed1.getText().toString());

SEO Secrets Uncovered

SEO Secrets Uncovered

Announcing an important message for Webmasters. Who Else Wants to Generate Massive Traffic and Crank Up the Exposure Their Websites Receive by Tapping Into the Unlimited Power of Today's Top Search Engines? As a webmaster, do you spend time studying the number of hits your website is receiving? Do you worry whether you and your clients are getting the exposure needed?

Get My Free Audio Book


Post a comment