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: and

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

More information on Google Asynchronous Javascript And XML (AJAX) search can be found at

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:

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="" 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" />


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/ package;

import; import; import; import; import; import;


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


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 = "";

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

tv1 = (TextView) this.findViewByld(; ed1 = (EditText) this.findViewByld(; bt1 = (Button) this.findViewByld(;

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


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

Log.v("Exception google search",


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);


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)


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


Google Search

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

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

National Basketball Association -Wikipedia, the free encyclopedia

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

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",


This excerpt can be added to the end of the 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());

Corner The Local Search Engine Market

Corner The Local Search Engine Market

Four Steps to Ensure your Business will Capitalize from Local Google Search Exposure. We live in an age where everyday more and more people are connecting online. The internet is more of a household necessity than passing fad.

Get My Free Ebook

Post a comment