Java tutorial
/* * Copyright (c) 2011 Daniel Huckaby * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.handlerexploit.news.data; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import android.net.http.AndroidHttpClient; import android.util.Log; public class YQLHelper { private static final String TAG = YQLHelper.class.getSimpleName(); public static String query(String query) { String fullUrl = null; try { fullUrl = "http://query.yahooapis.com/v1/public/yql?format=json&q=" + URLEncoder.encode(query, "US-ASCII"); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Error encoding URL", e); } if (fullUrl != null) { String queryResponse = null; try { String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; AndroidHttpClient androidHttpClient = AndroidHttpClient.newInstance(userAgent); // TODO Look into using something else for pre-froyo queryResponse = EntityUtils.toString(androidHttpClient.execute(new HttpGet(fullUrl)).getEntity()); androidHttpClient.close(); JSONObject jsonQuery = new JSONObject(queryResponse).getJSONObject("query"); if (jsonQuery.getInt("count") > 0) { return jsonQuery.getJSONObject("results").toString(); } else { Log.d(TAG, "YQL returned empty - " + fullUrl + " - " + jsonQuery.toString()); } } catch (Throwable e) { Log.e(TAG, "An error occured while parsing yql query - " + queryResponse, e); } } return null; } }